1

I have web application with several configuration classes.

@Configuration
public class ConfigA {

    @Bean(name = "bean_1")
    public MyBean getBean1() { /* Some code is here */ }

    @Bean(name = "bean_2")        
    public MyBean getBean2() { /* Some code is here */ }

    /* ... */

    @Bean(name = "bean_99")        
    public MyBean getBean99() { /* Some code is here */ }        
}

@Configuration
public class ConfigB {

    public OtherBean getOtherBean() { /* Some code is here */ }

}

Еach bean of class MyBean is registered in some global context when constructor is called. And OtherBean bean consumes this global context to get all instances of MyBean class. But spring creates OtherBean earlier then several of MyBean beans and I do not know how I can change this behavior.

PS:

  1. I do not want to inject all MyBean beans directly (explictly) in OtherBean, there are many MyBean beans.
  2. Now I have a solution: declare annotation @DependsOn({ "bean_1", "bean_2" .... "bean_99" }) on class ConfigB, but I think it is inconvenient (it is almost the same point 1).
  3. I think a solution could be force spring to create all declared beans (bean_1, ...) as soon as this configuration class (ConfigA) was discovered.
atott
  • 880
  • 10
  • 15
  • http://stackoverflow.com/questions/7868335/spring-make-sure-a-particular-bean-gets-initialized-first may help in your case – Jekin Kalariya Aug 31 '16 at 05:57
  • 2
    maybe try to add @Autowired List list; field to your configuration? This will inject all registered beans to a list so hopefully spring checks somehow where are those beans created. – hi_my_name_is Aug 31 '16 at 06:17
  • @freakman Thx, it solves my issue, if you post an answer (not a comment) I will mark it as correct answer. – atott Aug 31 '16 at 12:11

2 Answers2

1

add @Autowired List list; field to your configuration? This will inject all registered beans to a list so hopefully spring checks somehow where are those beans created.

hi_my_name_is
  • 4,894
  • 3
  • 34
  • 50
1

You can add the @Lazy here, this is the javadoc

If this annotation is not present on a @Component or @Bean definition, eager initialization will occur. If present and set to true, the @Bean or @Component will not be initialized until referenced by another bean or explicitly retrieved from the enclosing BeanFactory. If present and set to false, the bean will be instantiated on startup by bean factories that perform eager initialization of singletons.

Liping Huang
  • 4,378
  • 4
  • 29
  • 46