所以我有一个外部配置类,它使用我的 global.properties 文件中的属性注入(inject)变量。
我在 Spring boot 主类中实例化和访问该对象没有问题,但项目中的任何其他类都会使外部配置对象为空。
这就是我的外部配置类的样子
@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 类?
所有帮助将不胜感激!
最佳答案
您可以通过从属性中删除 @Autowired 并添加 setter 来完成此工作。
@Autowired
public void setExternalConfig(ExternalConfig externalConfig){
Http.externalConfig = externalConfig;
}
关于java - Spring引导 Autowiring 类不会在常规类中实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59732765/