Reputation: 446
I'm trying to build an app using Java EE 6. Development is done on TomEE 1.7. For various reasons, I have to create most of my CDI managed objects through a service producer. When I do this, however, the @PostConstruct
annotated method of the created bean is not invoked. If I take the service producer out of the way and let CDI create the object directly through its constructor, it does get called. Is this normal, or is it a bug of the CDI provider TomEE comes with (Open WebBeans)
Thanks
Upvotes: 2
Views: 1760
Reputation: 11723
Seems like bad practice to use a producer for everything - why are you using a producer if your classes are annotated with @PostConstruct
?
One way to do this is to use a creational context from within your producer method to provide a reference and then call post construct on that reference. Here's some sample code, taken from Apache DeltaSpike, a suite of CDI extensions:
BeanManager beanManager = getBeanManager();
CreationalContext creationalContext = beanManager.createCreationalContext(null);
AnnotatedType annotatedType = beanManager.createAnnotatedType(instance.getClass());
InjectionTarget injectionTarget = beanManager.createInjectionTarget(annotatedType);
injectionTarget.inject(instance, creationalContext);
injectionTarget.postConstruct(instance);
Upvotes: 0
Reputation: 18030
This is normal behavior. The @PostConstruct
method is called, when the bean is initialized by the container. See Weld Reference:
Simplifying just a little, things happen in this order:
First, the container calls the bean constructor (the default constructor or the one annotated
@Inject
), to obtain an instance of
the bean.Next, the container initializes the values of all injected fields of the bean.
- Next, the container calls all initializer methods of bean (the call order is not portable, don’t rely on it).
- Finally, the
@PostConstruct
method, if any, is called.
However in case of producer method you have full control, how the object is created, so you can call any needed method by yourself. Take notice, that in producer methods object is usually created using new
, so annotated fields are not initialized. Again check the producer method documentation for possible solution (injection into producer methods, @New
)
Upvotes: 3