我的 Spring Boot 应用程序具有以下应用程序结构:
- 来源
- 主要
- Java
- 资源
- 应用程序属性
- 主要
这是我的 application.properties 文件:
logging.level.org.springframework=TRACE
logging.level.org.hibernate=ERROR
spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**
#spring.resources.chain.cache=false
#spring.resources.chain.html-application-cache=false
#spring.headers.cache=false
language=java
我有一个类需要使用 language=java 属性。这就是我尝试使用它的方式:
public class EntityManager {
@Value("${language}")
private static String newLang;
public EntityManager(){
System.out.println("langauge is: " + newLang);
}
}
出于某种原因,打印的值总是“空”!我也试过把它放在类声明的顶部:
@PropertySource(value = "classpath:application.properties")
最佳答案
可以通过多种方式实现,引用下文。
@Configuration
@PropertySource("classpath:application.properties")
public class EntityManager {
@Value("${language}")
private static String newLang;
@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
return new PropertySourcesPlaceholderConfigurer();
}
}
或
@Configuration
@PropertySource("classpath:application.properties")
public class EntityManager {
@Autowired
private Environment env;
public void readProperty() {
env.getProperty("language");
}
}
关于java - 从 application.properties Spring Boot 中读取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45428826/