gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-01 23:07:59 29 4
gpt4 key购买 nike

目标.java:

package me;

@Component
public class Target implements Runnable {
@Autowired
private Properties properties;

public Target(){
properties.getProperty('my.property');
}

public void run() {
//do stuff
}
}

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

最佳答案

你正在做现场注入(inject)。您在构造函数中引用“待 Autowiring ”实例变量。在构造函数中,properties 字段为空,因为它尚未 Autowiring 。您可以使用构造函数注入(inject)。

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

关于java - Spring @Autowired bean 没有初始化;空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36418606/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com