Java 未在`@Configuration`注释类中注入应用程序上下文
我有如下设置:Java 未在`@Configuration`注释类中注入应用程序上下文,java,spring,Java,Spring,我有如下设置: @Configuration public class MyConfig { @Autowired ApplicationContext applicationContext; @Bean public MyBean myBean() { return applicationContext.getAutowireCapableBeanFactory().createBean(MyBean.class); } } 我一启
@Configuration
public class MyConfig {
@Autowired
ApplicationContext applicationContext;
@Bean
public MyBean myBean() {
return applicationContext.getAutowireCapableBeanFactory().createBean(MyBean.class);
}
}
我一启动应用程序,Spring就尝试创建myBean
,甚至在注入applicationContext
之前。由于后者是null
,它将导致方法myBean()
中出现NullPointerException
奇怪的是,注入应用程序上下文可以在其他一些@Configuration
类中工作,但不能在上面提到的类中工作
有没有办法在调用方法
myBean()
之前强制注入applicationContext
?我认为您不能保证在调用@Bean
声明的方法之前,始终加载使用@Autowired
声明的字段
要确保对ApplicationContext
对象进行赋值,可以使配置类实现ApplicationContextAware
@Configuration
public class MyConfig implements ApplicationContextAware {
private ApplicationContext context;
public void setApplicationContext(ApplicationContext context) {
this.context = context;
}
...
}
请发一封信。这是在非常罕见的情况下发生的。我的配置类看起来像这样,只是变量名已经交换了。然而,找出参与该问题的确切组件、配置文件或测试类运行程序可能需要几天时间。Spring
@configuration
类显然需要一个无参数构造函数,但是,实现ApplicationContextAware
是可行的。仍然不明白发生了什么。关于无参数构造函数,我从未尝试过,但令人惊讶的是,文档显示了一个参数构造函数示例: