Why is PostConstruct not called?
I had the same problem in my application. You didn't post your bean context configuration xml file (so I'm not sure if it's the same issue) but in my case adding this line:
<context:annotation-config/>
Solved my problem.
You need either <context:annotation-config/>
or <context:component-scan/>
to enable @PostConstruct annotation.
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.)
Since this question comes up first on Google for "postconstruct not called", another reason a @PostConstruct
method might not be called besides using the new
keyword instead of putting @PostConstruct
in a Spring bean is if you have a circular dependency.
If this bean were to depend on another bean that depended on this bean, your other bean might call addNewEntry()
before BlogEntryDao
was initialized, even though BlogEntryDao is a dependency for that other bean.
This is because Spring didn't know which bean you wanted to load first due to the circular reference. In this case, one can remove the circular reference or use @AutoWired
/@Value
constructor parameters instead of member values or setters, or if using xml configuration, maybe you can swap the order in which the beans are defined.