Spring 引导:从 "application.properties" 读取文件路径

Spring boot: Read a file PATH from "application.properties"

我正在使用 Spring Boot,我想从 resources/application.properties 文件中读取文件路径并将其值设置为 Java [=38 中的字符串=]:

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

当我尝试打印字符串时,它总是打印 "null"。我究竟做错了什么?谢谢。

资源文件夹是否在class路径中?如果不是这样试试

<bean id="propertyLoader" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
            <value>classpath:application.properties</value>
    </property>
</bean>

我假设您的 属性 文件与它引用的配置文件位于同一位置。

我终于解决了这个问题。我试图使用 "main" 线程(从主函数执行代码的线程)中的值注释。

例如,如果我从服务代码中获取值,效果会很好。