java - Why is PostConstruct not called? -


i working on simple java ee application.

i have class 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 managed bean calls method. until here no problems. since initialize method not called, getting npe in em.persist.

why initialize method not being called? running on glassfish server.

regards.

the java ee bean annotations such @postconstruct apply container-managed beans. if calling new blogentrydao yourself, container isn't going intercept creation , call @postconstruct method.

(furthermore, you'd better off using @persistencecontext or @persistenceunit instead of manually fetching entitymanagerfactory in initialize() method, , should creating entitymanager each call addnewentry(), since they're short-lived. making these changes eliminate need initialize() @ all.)


Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -