I am working on a simple Java EE application.
I have class like this:
import javax.annotation.PostConstruct; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; @Stateless public class BlogEntryDao { EntityManager em; @PostConstruct public void initialize(){ EntityManagerFactory emf = Persistence.createEntityManagerFactory("Persistence"); em = emf.createEntityManager(); } public void addNewEntry(){ Blogentry blogentry = new Blogentry(); blogentry.setTitle("Test"); blogentry.setContent("asdfasfas"); em.persist(blogentry); } }
So my managed bean calls this method. Until here no problems. But since the initialize method is not called, I am getting an NPE in em.persist.
Why is the initialize method not being called? I am running this on Glassfish server.
Regards.
Annotation Type PostConstruct The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization. This method MUST be invoked before the class is put into service. This annotation MUST be supported on all classes that support dependency injection.
2. @PostConstruct. Spring calls the methods annotated with @PostConstruct only once, just after the initialization of bean properties.
In jdk9 @PostConstruct and @PreDestroy are in java. xml. ws. annotation which is deprecated and scheduled for removal.
If a PostConstruct interceptor method returns a value, it is ignored by the container. 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.
The Java EE bean annotations such as @PostConstruct
only apply to container-managed beans. If you are simply calling new BlogEntryDao
yourself, the container isn't going to intercept the creation and call the @PostConstruct
method.
(Furthermore, you'd be better off using @PersistenceContext
or @PersistenceUnit
instead of manually fetching the EntityManagerFactory
in your initialize()
method, and you should be creating an EntityManager
for each call to addNewEntry()
, since they're short-lived. Making these changes would eliminate the need for initialize()
at all.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With