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

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

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

}

您正在进行字段注入。您在构造函数中引用 "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
    }
}