从application.properties Spring Boot读取值

Kar*_*ran 4 java spring spring-mvc

我的Spring启动应用程序具有以下应用程序结

  • SRC
    • 主要
      • java的
      • 资源
        • application.properties

这是我的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
Run Code Online (Sandbox Code Playgroud)

我有一个类需要使用该语言= java属性.这就是我尝试使用它的方式:

public class EntityManager {

    @Value("${language}")
    private static String newLang;

    public EntityManager(){
        System.out.println("langauge is: " + newLang);
    }
}
Run Code Online (Sandbox Code Playgroud)

由于某种原因,该打印值始终为"null"!我也试过把它放在类声明之上:

@PropertySource(value = "classpath:application.properties")
Run Code Online (Sandbox Code Playgroud)

小智 13

它可以通过多种方式实现,请参阅下文.

@Configuration
@PropertySource("classpath:application.properties")
public class EntityManager {

    @Value("${language}")
    private static String newLang;

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
        return new PropertySourcesPlaceholderConfigurer();
    }

}
Run Code Online (Sandbox Code Playgroud)

要么

@Configuration
@PropertySource("classpath:application.properties")
public class EntityManager {

    @Autowired
    private Environment env;

    public void readProperty() {
        env.getProperty("language");
    }

}
Run Code Online (Sandbox Code Playgroud)


小智 5

如果您正在使用Spring启动,则不需要@PropertySource("classpath:application.properties")使用spring boot starter parent,只需删除该static关键字即可开始工作.


Bar*_*ath 3

类顶部缺少构造型注释

@Component
public class EntityManager {

    @Value("${language}")
    private static String newLang;

    public EntityManager(){
        System.out.println("langauge is: " + newLang);
    }
}
Run Code Online (Sandbox Code Playgroud)