簡體   English   中英

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

你正在進行野外注射。 您在構造函數中引用了“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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM