How to get a bean from outside in java config

I have a java configuration class that imports XML files with @ImportResources annotation. In java config, I would like to reference the beans that are defined in the xml configuration, for example. as:

@Configuration @ImportResource({ "classpath:WEB-INF/somebeans.xml" } ) public class MyConfig { @Bean public Bar bar() { Bar bar = new Bar(); bar.setFoo(foo); // foo is defined in somebeans.xml return bar; } } 

I would like to set the bean foo, which was defined in somebeans.xml, to the bean panel that will be created in the java config class. How to get foo bean?

+4
source share
1 answer

Either add the field to your configuration class and annotate it with @Autowired , or add @Autowired to the method and pass the type argument.

 public class MyConfig { @Autowired private Foo foo; @Bean public Bar bar() { Bar bar = new Bar(); bar.setFoo(foo); // foo is defined in somebeans.xml return bar; } } 

or

 public class MyConfig { @Bean @Autowired public Bar bar(Foo foo) { Bar bar = new Bar(); bar.setFoo(foo); // foo is defined in somebeans.xml return bar; } } 

All this is explained in the reference guide .

+10
source

Source: https://habr.com/ru/post/1501282/


All Articles