spring mvc中的@propertysource
2024-08-31 07:24:36
在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 {
//...
}
最新文章
- Javascript的二进制数据处理学习 ——nodejs环境和浏览器环境分别分析
- [MySQL性能优化系列]提高缓存命中率
- MySQL 基础语句
- <;a>;每次点击都会让浏览器重新打开一个窗口问题
- Linq专题之创建Linq查询表达式
- 使用culr
- imx6 u-boot.bin 和 u-boot.imx
- 如何实现.so共享库文件
- oracle 表查询(2)
- hadoop2对比hadoop1
- Qunit 和 jsCoverage使用方法
- python解析json文件之简介
- 【C#】【对象转XML】xml序列化
- Hystrix系列-5-Hystrix的资源隔离策略
- OCM_第十二天课程:Section6 &mdash;》数据库性能调优_ 资源管理器/执行计划
- RuntimeError: Broken toolchain: cannot link a simple C program
- Pusher 消息推送测试工具
- select元素添加option的add()方法 | try{}catch{}
- struts2框架之自定义拦截器和配置
- is_palindrome 回文递归
热门文章
- 【POJ 3460】 Booksort
- B1391 [Ceoi2008]order 最大权闭合图 最小割
- 77.招聘信息管理 EXTJS 页面
- nested exception is java.lang.NoClassDefFoundError: net/sf/cglib/proxy/CallbackFilter
- Linux下查看操作系统的位数和系统名称版本信息
- bzoj1606[Usaco2008 Dec]Hay For Sale 购买干草(01背包)
- [Luogu2324]八数码难题
- Spring Boot (15) pom.xml设置
- Pull-up resistors
- VHDL之concurrent之operators