Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is PostConstruct not called?

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.

like image 366
Koray Tugay Avatar asked Aug 10 '13 12:08

Koray Tugay


People also ask

When PostConstruct is called?

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.

How many times is PostConstruct called?

2. @PostConstruct. Spring calls the methods annotated with @PostConstruct only once, just after the initialization of bean properties.

Is PostConstruct deprecated?

In jdk9 @PostConstruct and @PreDestroy are in java. xml. ws. annotation which is deprecated and scheduled for removal.

Should PostConstruct be public?

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.


1 Answers

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.)

like image 57
chrylis -cautiouslyoptimistic- Avatar answered Sep 20 '22 09:09

chrylis -cautiouslyoptimistic-