Spring @Autowired bean没有初始化;空指针异常

时间:2016-04-05 06:23:29

标签: java spring dependency-injection nullpointerexception autowired

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)
 ....

2 个答案:

答案 0 :(得分:3)

你正在进行野外注射。您在构造函数中引用了“to-be-autowired”实例变量。在构造函数中,properties字段为空,因为它尚未自动装配。您可以使用构造函数注入。

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
    }
}

答案 1 :(得分:2)

在设置属性之前调用构造函数。在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
   }

}