How to get externally defined bean in java config

若如初见. 提交于 2019-12-12 11:01:38

问题


I have a java config class that imports xml files with the @ImportResources annotation. In the java config I'd like to reference to beans that are defined in the xml config, e.g. like:

@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'd like to set the bean foo that has been defined in somebeans.xml to the bar bean that will be created in the java config class. How do I get the foo bean?


回答1:


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

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;
    }
}

This is all explained in the reference guide.



来源:https://stackoverflow.com/questions/18696771/how-to-get-externally-defined-bean-in-java-config

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!