我想在 MyComponent 类中使用 ApplicationContext 实例。当我尝试 Autowiring 时,Spring 在启动时初始化我的组件时出现空指针异常。
有什么方法可以在 MyComponent 类中 Autowiring ApplicationContext 吗?
@SpringBootApplication
public class SampleApplication implements CommandLineRunner {
@Autowired
MyComponent myComponent;
@Autowired
ApplicationContext context; //Spring autowires perfectly at this level
public static void main(String[] args) {
SpringApplication.run(SampleApplication.class, args);
}
}
@Component
public class MyComponent{
@Autowired
ApplicationContext ctx;
public MyComponent(){
ctx.getBean(...) //throws null pointer
}
}
最佳答案
如果您想确保您的依赖项(bean)已在构造函数中初始化并准备就绪,您应该使用构造函数注入(inject),而不是字段注入(inject):
@Autowired
public MyComponent(ApplicationContext ctx){
ctx.getBean(...) // do something
}
另一种方法是使用 @PostConstruct
如下所示:
@Component
public class MyComponent {
@Autowired
ApplicationContext ctx;
public MyComponent(){
}
@PostConstruct
public void init() {
ctx.getBean(...); // do something
}
}
你得到NPE
是因为spring需要先创建bean(MyComponent
)然后设置字段的值,所以在构造函数中,你的字段的值为空
。
关于java - 如何从 Component 注入(inject) ApplicationContext?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58656057/