gpt4 book ai didi

Spring Bean : Is autowired attribute initialised before constructor?

转载 作者:行者123 更新时间:2023-12-04 11:51:32 25 4
gpt4 key购买 nike

@Component
public class BeanA {
...
}


@Component
public class BeanB {

@Autowired
BeanA beanA;

public BeanB() {
// Use beanA
beanA.method();
}
}

我们可以假设在调用BeanB构造函数之前已创建并初始化BeanA吗? (我知道我们可以将BeanA作为构造函数arg传递给BeanB,这更多是出于了解spring/java初始化序列的好奇心问题)

最佳答案

看看http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-autowired-annotation-qualifiers
在Bean上设置属性将在之后通过进行,它是通过构造函数或工厂方法构造的。默认情况下,bean的名称为autowired,而值是使用setter方法设置的。因此,在您的情况下,该字段将在构造函数之后设置。
这是因为

@Autowired
BeanA beanA;
确实意味着您要自动连接该类实例的 字段。在您的情况下, beanA实际上不是构造函数arg。
(嗯,这是一个简单的问题,在编译后是否保留构造函数参数名称?是否有与此相关的调试标志?)
spring documentation的示例所示,您可以将 @Autowired应用于构造函数和字段:
public class MovieRecommender {

@Autowired
private MovieCatalog movieCatalog;

private CustomerPreferenceDao customerPreferenceDao;

@Autowired
public MovieRecommender(CustomerPreferenceDao customerPreferenceDao) {
this.customerPreferenceDao = customerPreferenceDao;
}

// ...

}
让我知道您是否需要更多帮助。
哦,这只是一个小问题。您似乎正在构造函数中的 beanA上调用method()。如果可以重写该方法,则不是一个好主意。我知道这只是您在这里记下的一个例子,但请注意。

关于 Spring Bean : Is autowired attribute initialised before constructor?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26230493/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com