【发布时间】:2015-10-16 08:40:48
【问题描述】:
我在我的 Spring MVC 项目中使用 Spring 3.1+ 版本。我已经阅读了一堆关于如何在代码中使用属性文件的文章,我尝试了一些解决方案,但没有一个是有效的。例如这样的http://websystique.com/spring/spring-propertysource-value-annotations-example/
以下是位于 src/main/resources 中的通信属性
doniiesuser.url=localhost
doniiesuser.port=8080
配置类,我用 spring mvc 配置重用了这个类,我尝试只为属性源添加一个不同的类。
<!-- 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();
}
}
添加属性文件读取的新更改是 @PropertySource 和 PropertySourcesPlaceholderConfigurer 方法
最后,我想在 @Service 或 @Controller 类中使用此属性(尝试 2 种解决方案,使用占位符 ${key} 和 Environment 类)
@Service
public class UserRepositoryUserDetailsService implements UserDetailsService{
private static Logger logger = LoggerFactory.getLogger(UserRepositoryUserDetailsService.class);
@Value( "${doniiesuser.url}" )
private String doniiesuserUrl;
@Value( "${doniiesuser.port}" )
private String doniiesuserPort;
@Autowired
private Environment environment;
//More things...
@Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
System.out.println("WEB - placeholder @value: " + doniiesuserUrl);
System.out.println("WEB - using env @value: " + environment.getProperty("doniiesuser.port"));
logger.info("WEB - placeholder @value: " + doniiesuserUrl);
logger.info("WEB - using env @value: " + environment.getProperty("doniiesuser.port"));
}
//....
}
当我在本地 tomcat 服务器上运行它时,日志会显示以下内容:
WEB - placeholder @value: ${doniiesuser.url}
WEB - using env @value: null
INFO - WEB - placeholder @value: ${doniiesuser.url}
INFO - WEB - using env @value: null
我错过了什么吗?有什么不明白的地方吗?
谢谢
【问题讨论】:
标签: java spring spring-mvc config