Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@PostConstruct method is not called in Spring

Tags:

SampleBean:

package com.springexample;  import javax.annotation.PostConstruct; import javax.annotation.PreDestroy;  public class SampleBean {      private BeanTypeOne beanOne;      private BeanTypeTwo beanTwo;      public void init() {          System.out.println("This is from the init() method");     }      @PostConstruct     public void initAnnotation() {          System.out.println("This is from the initAnnotation() method");      } 

and config file like this :

<bean id="SampleBean" class="com.springexample.SampleBean">     <property name="beanOne" ref="beanOneOne"></property>     <property name="beanTwo" ref="beanTwoOne"></property> </bean> 

And I don't have default-init-method attribute set on the beans tag.

Can any body tell why the @PostConstruct method does not get called.

like image 530
javanoob Avatar asked Aug 08 '10 13:08

javanoob


People also ask

When @PostConstruct is called in Java?

Methods marked with the @PostConstruct will be invoked after the bean has been created, dependencies have been injected, all managed properties are set, and before the bean is actually set into scope.

How many times a @PostConstruct method is called?

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

What does @PostConstruct do in spring?

When we annotate a method in Spring Bean with @PostConstruct annotation, it gets executed after the spring bean is initialized. We can have only one method annotated with @PostConstruct annotation. This annotation is part of Common Annotations API and it's part of JDK module javax.

Is @PostConstruct deprecated?

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


1 Answers

You need <context:annotation-config/> (or <context:component-scan/>) to enable @PostConstruct handling.

like image 67
axtavt Avatar answered Sep 20 '22 03:09

axtavt