[英]How can I access Spring beans in no-arg constructor?
@Component
public class MyClass {
public MyClass() {
SomeInterface something;
// Spring magic that i don't know
something.toString();
}
}
What Spring magic do I need to use to inject a bean into "something"? 将bean注入“某物”中,我需要使用什么Spring魔术?
I also wouldn't mind if it was a field. 我也不介意这是否是一个领域。 It just has to be usable from within the constructor! 它只必须在构造函数中可用!
The basic rules also apply to Spring: 基本规则也适用于Spring:
This thus leaves two choices: 因此,这留下了两个选择:
constructor injection: 构造函数注入:
@Autowired public MyClass(SomeInterface something) { // use something }
post-construct method, called after all the injections have been done, whatever the way: post-construct方法,在完成所有注入后以任何方式调用:
@Autowired private SomeInterface something; @PostConstruct private void initialize() { // use something }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.