java - @Autowired 和 bean 创建顺序

标签 java spring autowired

是否可以在创建其他依赖 bean 之前避免使用 @Autowire 一些 bean?让我用一个例子更好地解释它:

我有一个 FactoryBean,它创建一个 A 类型的对象,该对象具有一个名为 a 的属性。如果该属性为 null,它会为 bean A 分配一个默认值。

在@Configuration 类中我有:


    @Autowired
    private A myBean;

What is happening is that the factory creates the bean (I don't fully understand how) but the field a in the factory is null and I need that it takes another bean that it's used to create A. I can't add any annotation to the Factory since it's inside of an external dependency.

The thing is that I need to set the value of a before the @Autowired requests the object to the factory. Is it possible given the restrictions I have?

edit Heres the code:

@Configuration
@ImportResource("classpath:factory-context.xml")
public class ServiceContextConfig {
    @Autowired
    private A createdObject;

    @Bean(name = "entities-list")
    public List<String> getEntity() {
        List<String> ls = new ArrayList<String>();
        ls.add("countriescatalog");
        return ls;
    }

然后 factory-context.xml 看起来像这样:

<bean id="client-factory" class="ClientFactory">
    <property name="entities" ref="entities-list"/>
</bean>

其实配置有点大。我没有尝试使用这样的简化示例。我将尝试使用像这样的简化上下文来重现它,看看我是否可以按照@emd 的建议修复它包装工厂

最佳答案

希望我正确理解了这个问题。但是这里有一个你可以做什么的例子:

把工厂包装在自己的工厂里。在您自己的工厂中 Autowiring 该字段。用原始工厂构造对象,注入(inject)字段并返回对象。

例子:

public class MyFactory {

    @Autowired
    private A a;

    private final OriginalFactory originalFactory;

    public MyFactory(OriginalFactory originalFactory) {
        this.originalFactory=originalFactory;
    }

    public CreateObject getInstance() {

        CreatedObject createdObject = originalFactory.getInstance();
        createdObject.setA(a);

        return createdObject;
    }
}

Spring 部分:

<bean id="myFactory" class="aa.aa.MyFactory">
    <constructor-arg ref="originalFactory" />  
</bean>         
<bean id="createdObject" factory-bean="myFactory" factory-method="getInstance"/>

关于java - @Autowired 和 bean 创建顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15558338/

相关文章:

java - Spring在运行时添加占位符值

java - 使用 Spring Batch 将文件中的日期解析为 LocalDateTime

Java ServiceImpl 方法不断返回 null

java - 如何在 jlabel 之间留空格?

java - 如何每小时调用一次函数?另外,我怎样才能循环这个?

java - 由同一对象同步的 Wait-Notify 不起作用

java - @OneToMany 删除 child

java - Math.E 和 e 有什么区别

java - Spring 启动: Autowired error

java - Spring @Autowired 检测