【问题标题】:In Spring, can I autowire new beans from inside an autowired bean?在 Spring 中,我可以从自动装配的 bean 中自动装配新的 bean 吗?
【发布时间】:2011-01-23 21:39:13
【问题描述】:

我通常只是将@Autowire 东西放入弹簧对象中。但是我遇到了一种情况,我需要动态创建一些需要可以自动装配的值的对象。

我该怎么办?我能做的就是手动将自动装配的值传递给新对象的构造函数。我想做的只是在创建每个新对象时自动装配它。

@Service
public class Foo {
    @Autowired private Bar bar;

    /** This creates Blah objects and passes in the autowired value. */
    public void manuallyPassValues() {
        List<Blah> blahs = new LinkedList<Blah>();
        for(int i=0; i<5; ++i) {
            Blah blah = new Blah(bar);
            blahs.add(blah);
        }
        // ...
    }

    /** This creates Blah objects and autowires them. */
    public void useAutowire() {
        List<Blah> blahs = new LinkedList<Blah>();
        for(int i=0; i<5; ++i) {
            // How do I implement the createAutowiredObject method?
            Blah blah = createAutowiredObject(Blah.class);
            blahs.add(blah);
        }
        // ...
    }
}

理想情况下,我不会在此 bean 中包含任何配置信息。它是自动装配的,因此它需要对新 bean 进行自动装配的任何对象都应该通过自动装配来提供给它。

【问题讨论】:

    标签: java spring autowired


    【解决方案1】:

    你可以使用AutowireCapableBeanFactory:

    @Service 
    public class Foo { 
        @Autowired private AutowireCapableBeanFactory factory; 
    
        private <T> T createAutowiredObject(Class<T> c) {
            return factory.createBean(c);
        }
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 2018-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-27
      • 1970-01-01
      • 2020-09-09
      • 2018-06-15
      相关资源
      最近更新 更多