I have a problem with my Spring Classes. I need to get all Beans of a type inside a Configuration class to give them to a another class.
The Problem now is, that I cant do that unless I startup a ApplicationContext but that doesn’t work, because the Config class I call up uses the config class I’m calling from, so I get a endless loop…
as example:
@Configuration
@Import(Calling.class)
public class MyConfig{
@Bean
public ExampleClass aBean(){
...
return aObject;
}
}
@Configuration
@Import(MyConfig.class)
public class Calling{
@Bean
public Foo anotherBean(){
ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(myConfig.class);
ctx.getBeansOfType(ExampleClass.class);
return aObject;
}
}
Is there any functionality or pattern I can use to get these Beans?
With
@Configuration, you need to be very careful not to “pull” beans from the context, since you often get these infinite loops.Try this instead:
This declarative approach should hopefully get around the infinite loop problem.
Note also, you should avoid cyclic
@Import. Do it in one direction only, as in the above example.