users@jersey.java.net

[Jersey] Re: _at_PostConstruct not executed on Providers?

From: Pavel Bucek <pavel.bucek_at_oracle.com>
Date: Mon, 30 Jan 2012 09:07:28 +0100

Hello Martynas,

it should work, but I guess there is problem with your @PostConstruct
method siganture. Runtime looks for method with void return type and no
params (actually, quoting javadoc:
""
The method on which the PostConstruct annotation is applied MUST fulfill
all of the following criteria - - The method MUST NOT have any
parameters except in the case of EJB interceptors in which case it takes
an InvocationC ontext object as defined by the EJB specification. - The
return type of the method MUST be void. - The method MUST NOT throw a
checked exception. - The method on which PostConstruct is applied MAY be
public, protected, package private or private. - The method MUST NOT be
static except for the application client. - The method MAY be final. -
If the method throws an unchecked exception the class MUST NOT be put
into service except in the case of EJBs where the EJB can handle
exceptions and even recover from them.
""
), so I would recommend you to create ServletContext field and use it in
your @PostConstruct method:

     @Context
     private ServletContext context

     @PostConstruct
     public void init()
     {
            logger.log(Level.INFO, "@PostConstruct");
            xslt = XSLTBuilder.fromStylesheet(getStylesheet(this.context,
XSLT_BASE + "index.xsl")).
     }

Regards,
Pavel


On 1/28/12 1:37 PM, Martynas Jusevicius wrote:
> Hey list,
>
> I have a MessageBodyWriter class, which uses @PostConstruct to
> initialize XSLT stylesheet located in the local WEB-INF folder and
> accessed via ServletContext:
>
> @Provider
> @Singleton
> @Produces({MediaType.TEXT_HTML})
> public class ResourceXSLTWriter implements MessageBodyWriter<Resource>
> {
> public static final String XSLT_BASE = "/WEB-INF/xsl/";
>
> private XSLTBuilder xslt = null;
>
> @PostConstruct
> public void init(@Context ServletContext context)
> {
> logger.log(Level.INFO, "@PostConstruct");
> xslt = XSLTBuilder.fromStylesheet(getStylesheet(context,
> XSLT_BASE + "index.xsl")).
> }
>
> // ... more code
> }
>
> It is initialized as a Singleton in the Application:
>
> @Override
> public Set<Object> getSingletons()
> {
> singletons.add(new ResourceXSLTWriter());
>
> return singletons;
> }
>
> However I can see that @PostConstruct is never called, therefore xslt
> variable stays null and writeTo() throws an exception later on.
>
> Anything I'm doing wrong?
>
> Martynas
> graphity.org
>