如何保证在构造函数中可以访问Spring @Autowired注入

时间:2012-11-06 14:38:14

标签: spring code-injection

我有一个带有@Autowired setter getter注入的Spring Bean。但是,当我尝试访问注入的bean时,我得到NullPointerException,因为注入的bean没有真正注入。

有没有办法保证在结构调用之前完成注射?

@Component
@Scope("session")
public class A{

@Autowired
B;

public A()
{
//B is null here, because it has not been injected yet.
}

//Setter Getters
}

1 个答案:

答案 0 :(得分:4)

使用@PostConstruct注释。这将在Spring初始化bean之后立即调用。

@Autowired
B b;

public A() {
}

@PostConstruct
public void doAfterConstructorIsCalled() {
    b.do();
}

来自javax.* API