【发布时间】:2020-05-01 02:51:49
【问题描述】:
所以我有一个外部配置类,它从我的 global.properties 文件中注入具有属性的变量。
我在 Spring boot 主类中实例化和访问对象没有问题,但我项目中的任何其他类都会使外部配置对象为 null。
这就是我的外部配置类的样子
@Component
@PropertySource("classpath:global.properties")
public class ExternalConfig {
@Value("${developerName}")
private String developerName;
//getters and setters
public String getDeveloperName() {
return developerName;
}
public void setDeveloperName(String developerName) {
this.developerName = developerName;
}
}
这是我的 Spring boot 主类
@SpringBootApplication
public class SpringBootMain implements CommandLineRunner {
@Autowired
private ExternalConfig externalConfig;
@Bean
ResourceConfig resourceConfig() {
return new ResourceConfig().registerClasses(Version1Api.class, Paypal.class);
}
public static void main(String[] args) {
SpringApplication.run(SpringBootMain.class);
}
@Override
public void run(String... args) throws Exception {
// TODO Auto-generated method stub
System.out.println("RUN METHOD");
System.out.println(externalConfig.getDeveloperName());
}
}
但是,如果我尝试将此外部配置类添加到另一个类,例如我的 HTTP 类
@Component
public class Http {
Http() {
}
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(Version1Api.class);
@Autowired
private static ExternalConfig externalConfig;
public static void main(String[] args) throws IOException, URISyntaxException {
logger.info("HTTP Class");
logger.info(externalConfig.getDeveloperName());
}
该对象始终为空并给我一个错误。我究竟做错了什么?我应该以不同的方式实现我的对象吗?
或者我应该以不同的方式实现我的 HTTP 类吗?
所有帮助将不胜感激!
【问题讨论】:
-
您不能自动装配静态字段,也不能在 thge
main方法中使用。
标签: java spring spring-boot configuration autowired