从 application.properties Spring Boot 中读取值

新手上路,请多包涵

我的 Spring Boot 应用程序具有以下应用程序结构:

  • 来源
    • 主要的
      • 爪哇
      • 资源
        • 应用程序.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

我有一个类需要使用 language=java 属性。这就是我尝试使用它的方式:

 public class EntityManager {

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

    public EntityManager(){
        System.out.println("langauge is: " + newLang);
    }
}

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

 @PropertySource(value = "classpath:application.properties")

原文由 Karan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 495
1 个回答

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

 @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");
    }

}

原文由 Anil Kumar Athuluri 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题