[英]Spring @Autowired bean not initialising; Null Pointer Exception
Target.java:
package me;
@Component
public class Target implements Runnable {
@Autowired
private Properties properties;
public Target(){
properties.getProperty('my.property');
}
public void run() {
//do stuff
}
}
Config.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)
....
你正在进行野外注射。 您在构造函数中引用了“to-be-autowired”实例变量。 在构造函数中, properties
字段为null,因为它尚未自动装配。 您可以使用构造函数注入。
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
}
}
在设置属性之前调用构造函数。 在spring设置之前,您正在构造函数中调用属性上的方法。 使用类似PostConstruct的东西:
package me;
@Component
public class Target implements Runnable {
@Autowired
private Properties properties;
public Target(){}
@PostConstruct
public void init() {
properties.getProperty('my.property');
}
public void run() {
//do stuff
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.