retrieve Bean programmatically

后端 未结 3 1330
有刺的猬
有刺的猬 2020-12-10 12:17
@Configuration
public class MyConfig {
    @Bean(name = \"myObj\")
    public MyObj getMyObj() {
        return new MyObj();
    }
}

I have this My

3条回答
  •  抹茶落季
    2020-12-10 13:05

    The simplest (though not the cleanest) approach if you really need to fetch beans from the ApplicationContext is to have your class implement the ApplicationContextAware interface and provide the setApplicationContext() method.

    Once you have a reference to the ApplicationContext you have access to many methods that will return bean instances to you.

    The downside is that this makes your class aware of the Spring context, which one should avoid unless necessary.

提交回复
热议问题