在spring mvc中,在配置文件中的东西,可以在java代码中通过注解进行读取了:

@PropertySource  在spring 3.1中开始引入

比如有配置文件

config.properties

mongodb.url=1.2.3.4

mongodb.db=hello

则代码中

@PropertySource("classpath:config.properties")
public class AppConfigMongoDB { //1.2.3.4
@Value("${mongodb.url}")
private String mongodbUrl; //hello
@Value("${mongodb.db}")
private String defaultDb; @Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
return new PropertySourcesPlaceholderConfigurer();
}

则mongodbUrl已经是读取出1.2.3.4的值了,而spring提倡用env去读取值

@Autowired
private Environment env; String mongodbUrl = env.getProperty("mongodb.url");
String defaultDb = env.getProperty("mongodb.db");

要注意的是,要使用

@Bean

public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {

return new PropertySourcesPlaceholderConfigurer();

}

才能让spring正确解析出${} 中的值

在spring 3.2中,允许支持多个properties了,

@Configuration
@PropertySource({
"classpath:config.properties",
"classpath:db.properties" //如果是相同的key,则最后一个起作用
})
public class AppConfig {
@Autowired
Environment env;
}

spring 4.1中,支持@PropertySources

@Configuration
@PropertySources({
@PropertySource("classpath:config.properties"),
@PropertySource("classpath:db.properties")
})
public class AppConfig {
//...
}

在spring 4.2中,

@Configuration
@PropertySource("classpath:missing.properties")
public class AppConfig {
//...
}

如果发现missing.properties不存在,则抛出异常

,也可以使用ignoreResourceNotFound=true去忽略

@Configuration

@PropertySource(value="classpath:missing.properties", ignoreResourceNotFound=true)

public class AppConfig {

//...

}

最新文章

  1. Javascript的二进制数据处理学习 ——nodejs环境和浏览器环境分别分析
  2. [MySQL性能优化系列]提高缓存命中率
  3. MySQL 基础语句
  4. <a>每次点击都会让浏览器重新打开一个窗口问题
  5. Linq专题之创建Linq查询表达式
  6. 使用culr
  7. imx6 u-boot.bin 和 u-boot.imx
  8. 如何实现.so共享库文件
  9. oracle 表查询(2)
  10. hadoop2对比hadoop1
  11. Qunit 和 jsCoverage使用方法
  12. python解析json文件之简介
  13. 【C#】【对象转XML】xml序列化
  14. Hystrix系列-5-Hystrix的资源隔离策略
  15. OCM_第十二天课程:Section6 —》数据库性能调优_ 资源管理器/执行计划
  16. RuntimeError: Broken toolchain: cannot link a simple C program
  17. Pusher 消息推送测试工具
  18. select元素添加option的add()方法 | try{}catch{}
  19. struts2框架之自定义拦截器和配置
  20. is_palindrome 回文递归

热门文章

  1. 【POJ 3460】 Booksort
  2. B1391 [Ceoi2008]order 最大权闭合图 最小割
  3. 77.招聘信息管理 EXTJS 页面
  4. nested exception is java.lang.NoClassDefFoundError: net/sf/cglib/proxy/CallbackFilter
  5. Linux下查看操作系统的位数和系统名称版本信息
  6. bzoj1606[Usaco2008 Dec]Hay For Sale 购买干草(01背包)
  7. [Luogu2324]八数码难题
  8. Spring Boot (15) pom.xml设置
  9. Pull-up resistors
  10. VHDL之concurrent之operators