简体   繁体   English

无法在spring启动应用程序中读取application.properties

[英]Unable to read application.properties in spring boot application

I am unable to read application.properties value in my project in classes that are injected as a bean from another project. 我无法在从另一个项目注入bean的类中读取我的项目中的application.properties值。 My project is using another project which has classes which needs to read configuration from application.properties. 我的项目正在使用另一个项目,该项目具有需要从application.properties读取配置的类。 Mine is a maven project and a spring boot application having application.properties in src/main/resources folder and those properties values are defined in it. 我是一个maven项目和一个Spring引导应用程序,在src / main / resources文件夹中有application.properties,并在其中定义了这些属性值。 What is it that I am missing that it is unable to read file values? 我错过了什么,它无法读取文件值? Or is there is any other mechanism for setting these properties for classes loaded via component-scan 或者是否有任何其他机制为通过组件扫描加载的类设置这些属性

Below line of code works fine, it is able to read value from the application.properties: @PostConstruct void init() throws ClassNotFoundException, IOException { System.out.println(context.getEnvironment().getProperty("env.host", "default value")); 下面的代码行工作正常,它能够从application.properties读取值:@PostConstruct void init()抛出ClassNotFoundException,IOException {System.out.println(context.getEnvironment()。getProperty(“env.host”, “默认值”)); } }

Now there is another project which I am using in mine. 现在还有我正在使用的另一个项目。 When loading the classes those beans are getting initialized as dependency of another class, there also it tries to read same value in constants file as 当加载类时,那些bean被初始化为另一个类的依赖项,它也尝试在常量文件中读取相同的值

   static final String HOST_PROPERTY = "${env.host}";

There this value is not getting initialized to value from applictaion.properties 这个值没有从applictaion.properties初始化为值

If you want to get application.properties values,you have to two option. 如果要获取application.properties值,则必须有两个选项。 1) you can autowire Environment class and use its getProperty() method as 1)您可以自动装配Environment类并使用其getProperty()方法

@Autowired
Environment env;
env.getProperty("${env.host}");

2)@Value annotation 2)@Value注释

@Value("${env.host}")
    String HOST_PROPERTY;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM