retrieve Bean programmatically

后端 未结 3 1323
有刺的猬
有刺的猬 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 12:38

    Try this:

    public class Foo {
        public Foo(ApplicationContext context){
            context.getBean("myObj")
        }
    }
    
    public class Var {
        @Autowired
        ApplicationContext context;
        public void varMethod(){
                Foo foo = new Foo(context);
        }
    }
    
    0 讨论(0)
  • 2020-12-10 12:39

    Here an Example

    public class MyFancyBean implements ApplicationContextAware {
    
      private ApplicationContext applicationContext;
    
      void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
      }
    
      public void businessMethod() {
        //use applicationContext somehow
      }
    
    }
    

    However you rarely need to access ApplicationContext directly. Typically you start it once and let beans populate themselves automatically.

    Here you go:

    ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
    

    Note that you don't have to mention files already included in applicationContext.xml. Now you can simply fetch one bean by name or type:

    ctx.getBean("someName")
    

    Note that there are tons of ways to start Spring - using ContextLoaderListener, @Configuration class, etc.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题