I'm using Spring Boot and I want to read a file path from the resources/application.properties file and set its value to a String in a Java class:
我正在使用Spring Boot,我想从resources / application.properties文件中读取文件路径,并将其值设置为Java类中的String:
resources/application.properties
mypath=dir/file.ext
resources/application-context.xml
<context:property-placeholder location="classpath:application.properties" />
MyJavaClass.java
@Component
public class MyJavaClass{
@Value("${mypath}")
String mypath;
public void printme(){
System.err.println(mypath);
}
}
When I try to print the String, it always prints "null". What am I doing wrong? Thanks.
当我尝试打印String时,它总是打印“null”。我究竟做错了什么?谢谢。
2 个解决方案
#1
0
Is the resource folder in the class path? If not try like this
资源文件夹是类路径吗?如果不是这样尝试
<bean id="propertyLoader" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<value>classpath:application.properties</value>
</property>
</bean>
I assume like your property file is present in the same location as the configuration file from which it is referring.
我假设你的属性文件与它所引用的配置文件位于同一位置。
#2
-1
Finally I solved the problem. I was trying to use the value annotation from the "main" thread (the one that executes code from the main function).
最后我解决了这个问题。我试图使用“主”线程(从主函数执行代码的线程)中的值注释。
If I get the values from the code of the services for example, it works great.
例如,如果我从服务代码中获取值,则效果很好。
#1
0
Is the resource folder in the class path? If not try like this
资源文件夹是类路径吗?如果不是这样尝试
<bean id="propertyLoader" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<value>classpath:application.properties</value>
</property>
</bean>
I assume like your property file is present in the same location as the configuration file from which it is referring.
我假设你的属性文件与它所引用的配置文件位于同一位置。
#2
-1
Finally I solved the problem. I was trying to use the value annotation from the "main" thread (the one that executes code from the main function).
最后我解决了这个问题。我试图使用“主”线程(从主函数执行代码的线程)中的值注释。
If I get the values from the code of the services for example, it works great.
例如,如果我从服务代码中获取值,则效果很好。