property- placeholder

本文详细介绍了Spring中property-placeholder的使用,包括在XML和Java配置中的配置方式,以及@PropertySource注解的添加。同时,文章深入解析了Spring加载properties文件的过程,涉及到BeanDefinitionParser、BeanFactoryPostProcessor和PropertySourcesPlaceholderConfigurer等组件的作用。最后,讨论了PropertySourcesPlaceholderConfigurer如何实例化并处理bean definition中的占位符。
摘要由CSDN通过智能技术生成

**

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文件###

<?xml version="1.0" encoding="UTF-8"?>

  <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 配 置 文 件 中 获 取 <

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值