如何在Java Spring MVC应用程序中读取属性(或任何其他文本)文件?

Eed*_*doh 3 java spring-mvc

我需要在我的Spring MVC应用程序中读取java属性文件,但我找不到这样做的方法.我在这里尝试了类似问题的几个答案,但我没有成功.我是Java新手,尤其是Spring MVC,所以我可能搞砸了.

我不确定该文件是否已成功部署.我正在使用Tomcat btw.

mat*_*sev 10

如果您使用的是Spring 3.1+,则可以使用@PropertySource注释:

@Configuration
@PropertySource("classpath:/com/example/app.properties")
public class AppConfig {
    // create beans
}
Run Code Online (Sandbox Code Playgroud)

或者对于基于XML的配置,您可以使用<context:property-placeholder>:

<beans>
    <context:property-placeholder location="classpath:com/example/app.properties"/>
    <!-- bean declarations -->
</beans>
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用@Value注释在属性文件中自动装配密钥:

@Value("${property.key}") String propertyValue;
Run Code Online (Sandbox Code Playgroud)

阅读Spring参考文档中的更多详细信息.