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

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

解决方法:

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

}

上一篇:如何在java中按字母顺序对字符串数组进行排序?


下一篇:java – 如何在解析xml时检查空标签?