Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get all the beans in a method annotated with @PostConstruct?

Tags:

java

spring

As far as I know, A method annotated with @PostConstruct will be executed after its bean has been initialized.

So can I get all the beans in this method? Like this...

@CustomAnnotation
public class Foo {
}

@Service
public class TestBean {
   @Autowired
   private Application context;

   @PostContruct
   public void init() {
      // get all beans annotated with @CustomAnnotation
      context.getBeansWithAnnotation(CustomAnnotation.class);
      // to do something...
   }
}

If the TestBean is initialized before the Foo, does the Foo can be detected in init()?

like image 943
NewGeek Avatar asked Dec 05 '25 21:12

NewGeek


1 Answers

Spring initialization has at least two distinct steps when it comes to singleton beans.

Before the actual singleton bean instances are created, and your @PostConstruct method is called, the bean factory reads al the available configurations (e.g. XML files, Groovy scripts, @Configuration classes, other) and registers all the encountered bean definitions.

getBeansWithAnnotation() should find a Foo bean, if it wasn't created from it's bean definition before it will be created when you request it in @PostConstrust. You can try to force this scenario with @DependsOn however it may lead to circular dependency problem:

@Component
@DependsOn("testBean")
@CustomAnnotation
public class Foo {
}

@Service("testBean")
public class TestBean {

   @Autoware
   private Application context;

   @PostContruct
   public void init() {
      context.getBeansWithAnnotation(CustomAnnotation.class);
   }
}
like image 123
Karol Dowbecki Avatar answered Dec 07 '25 10:12

Karol Dowbecki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!