【发布时间】:2020-03-23 11:55:03
【问题描述】:
通过@Autowired,我无法访问具有 @Component 注释(第 1 步:方法)的其他 java 文件中的 @Component/@Service/@Respository/@Controller 类对象第 1 步方法获取 Null 指针异常,但我可以使用相同的方法实现(第 2 步:方法)。
谁能告诉我为什么我无法使用第 1 步方法实现:
仅供参考-我已经在整个项目中进行了搜索,我没有使用/调用/初始化 @Component 类,使用 new 自动装配类的方法仍然遇到“空指针异常”的问题
第 1 步:使用@Autowired 注解
@Component
public class Processor {
@Autowired
PropertyConfigurator propconfigrator; --> Getting here as null pointer Exception
public void getDetails(){
System.out.println ("Application URL +propconfigrator.getProperties().getProperty("appURL"));
}
}
第 2 步:使用带/不带 @AutoWired 注释的 ApplicationContext 接口。我能够从 PropertyConfigurator java 文件中获取属性值
@Component
public class Processor {
@Autowired
PropertyConfigurator propconfigrator = ApplicationContextHolder.getContext().getBean(PropertyConfigurator.class);
public void getDetails(){
System.out.println ("Application URL +propconfigrator.getProperties().getProperty("appURL"));
}
}
ApplicationContextHolder.java
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class ApplicationContextHolder implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
public static ApplicationContext getContext() {
return context;
}
}
PropertyConfigurator.java 文件
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
@Service
@Configurable
public class PropertyConfigurator {
private final Properties properties;
public Properties getProperties () {
return properties;
}
public PropertyConfigurator(){
properties = new Properties();
try {
properties.load(getClass().getClassLoader().getResourceAsStream("dbconfig.properties"));
} catch (IOException e) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, e.getMessage(), e);
}
}
}
【问题讨论】:
标签: spring-boot nullpointerexception autowired