目标.java:
package me;
@Component
public class Target implements Runnable {
@Autowired
private Properties properties;
public Target(){
properties.getProperty('my.property');
}
public void run() {
//do stuff
}
}
配置.java:
@Configuration
@ComponentScan(basePackages = {"me"})
public class Config {
@Bean(name="properties")
public PropertiesFactoryBean properties() {
PropertiesFactoryBean bean = new PropertiesFactoryBean();
bean.setLocation(new FileSystemResource("src/my.properties"));
return bean;
}
public static void main(String[] argv) throws Exception {
ApplicationContext context = new AnnotationConfigApplicationContext(Application.class);
Target t = context.getBean(Target.class);
t.run();
}
}
用上面的代码。栈底:
Caused by: java.lang.NullPointerException
at me.Target.<init>(Target.java:9)
....
最佳答案
你正在做现场注入(inject)。您在构造函数中引用“待 Autowiring ”实例变量。在构造函数中,properties
字段为空,因为它尚未 Autowiring 。您可以使用构造函数注入(inject)。
package me;
@Component
public class Target implements Runnable {
private final Properties properties;
@Autowired
public Target(Properties properties){
this.properties = properties;
properties.getProperty('my.property');
}
public void run() {
//do stuff
}
}
关于java - Spring @Autowired bean 没有初始化;空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36418606/