作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
@Component
public class BeanA {
...
}
@Component
public class BeanB {
@Autowired
BeanA beanA;
public BeanB() {
// Use beanA
beanA.method();
}
}
最佳答案
看看http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-autowired-annotation-qualifiers
在Bean上设置属性将在之后通过进行,它是通过构造函数或工厂方法构造的。默认情况下,bean的名称为autowired
,而值是使用setter方法设置的。因此,在您的情况下,该字段将在构造函数之后设置。
这是因为
@Autowired
BeanA beanA;
确实意味着您要自动连接该类实例的
字段。在您的情况下,
beanA
实际上不是构造函数arg。
@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/
我是一名优秀的程序员,十分优秀!