**
Spring中property-placeholder的使用与解析
**
Spring中property-placeholder的使用与解析#
我们在基于spring开发应用的时候,一般都会将数据库的配置放置在properties文件中.
代码分析的时候,涉及的知识点概要:
NamespaceHandler 解析xml配置文件中的自定义命名空间
ContextNamespaceHandler 上下文相关的解析器,这边定义了具体如何解析property-placeholder的解析器
BeanDefinitionParser 解析bean definition的接口
BeanFactoryPostProcessor 加载好bean definition后可以对其进行修改
PropertySourcesPlaceholderConfigurer 处理bean definition 中的占位符
我们先来看看具体的使用吧
property的使用##
在xml文件中配置properties文件###
<context:property-placeholder location="classpath:foo.properties" />
这样/src/main/resources/foo.properties文件就会被spring加载 如果想使用多个配置文件,可以添加order字段来进行排序
使用PropertySource注解配置###
Spring3.1添加了@PropertySource注解,方便添加property文件到环境.
@Configuration
@PropertySource(“classpath:foo.properties”)
public class PropertiesWithJavaConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
properties的注入与使用###
java中使用@Value注解获取
@Value( “${jdbc.url}” )
private String jdbcUrl;
还可以添加一个默认值
@Value( “ j d b c . u r l : a D e f a u l t U r l " ) p r i v a t e S t r i n g j d b c U r l ; 在 S p r i n g 的 x m l 配 置 文 件 中 获 取 <