使用基于java的变量从SpringMVC中的属性文件读取值
我在SpringMVC项目中使用Spring3.1+版本。我已经读了一大堆关于如何在代码中使用属性文件的文章,我尝试了一些解决方案,但没有一个是有效的。举个例子 以下是位于src/main/resources中的communication.properties使用基于java的变量从SpringMVC中的属性文件读取值,java,spring,spring-mvc,config,Java,Spring,Spring Mvc,Config,我在SpringMVC项目中使用Spring3.1+版本。我已经读了一大堆关于如何在代码中使用属性文件的文章,我尝试了一些解决方案,但没有一个是有效的。举个例子 以下是位于src/main/resources中的communication.properties doniiesuser.url=localhost doniiesuser.port=8080 配置类,我使用SpringMVC配置重用了该类,并尝试仅为属性源添加一个不同的类 <!-- language: java -->
doniiesuser.url=localhost
doniiesuser.port=8080
配置类,我使用SpringMVC配置重用了该类,并尝试仅为属性源添加一个不同的类
<!-- language: java -->
package com.doniies.doniiesweb.config;
import org.springframework.context.annotation.Bean;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"com.doniies.doniiesweb.controller", "com.doniies.doniiesweb.services"})
@PropertySource(value = {"classpath:communication.properties"})
public class MVCConfig extends WebMvcConfigurerAdapter{
// more beans and code
/**
* Ensures that placeholders are replaced with property values
*/
@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
当我在本地tomcat服务器上运行它时,日志将显示以下内容:
WEB - placeholder @value: ${doniiesuser.url}
WEB - using env @value: null
INFO - WEB - placeholder @value: ${doniiesuser.url}
INFO - WEB - using env @value: null
我错过什么了吗?有什么我不明白的吗
谢谢我想5个月后你一定解决了这个问题 我建议您检查“WebAppInitializer”是否正在加载所有配置文件,您可以使用以下方法:
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.scan("com.doniies.doniiesweb.config");
另一个需要检查的是“PropertiesConfiguration”文件,以防它引起一些冲突
我已经使用Spring4.2测试了一个配置,类似于您发布的文章中的配置,它工作正常
希望这有帮助
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.scan("com.doniies.doniiesweb.config");