PropertyPlaceholderConfigurer属性文件

1. 使用 PropertyPlaceholderConfigurer属性文件

在部署spring web项目的时候,配置属性文件是必不可少,对于springMVC项目 更是如此,一般会有dataSource相关配置,为了更灵活的配置jdbc相关属性。很多公司会抽取jdbc的属性到单独的文件中,方便以后修改。此时便用到了PropertyPlaceholderConfigurer属性文件

//jdbc.properties
url = jdbc:mysql://localhost:3306/databaseName
driver = com.mysql...
username = root
password = 123456

 //bean文件配置 此处使用p属性
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
    p:location="classpath:jdbc.properties"
    p:fileEncoding="UTF-8"/>
 //配置dataSource数据源
 <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
     p:name="${driver}"
     p:url="${url}"
     p:username="${username}"
     p:password="${password}"/>
     
  //PropertyPlaceholderConfigurer属性
  有locations 属性克配置指向多个文件
  fileEncoding 指定文件编码
  order 出现多个该属性时 指定顺序
  placeholderPrefix 指定前缀 默认 ${
  placeholderSuffix 指定后缀 默认 }
// 可以使用context标签配置 更方便 但不支持PropertyPlaceholderConfigurer高级属性 例如加密
//配置context
<context:property-placeholder location="classpath:jdbc.properties" />
//相关context属性
<context:component-scan base-package="基础包地址"/>

2. 注解使用配置文件的属性

可以使用注解 @Value("${username}") 获取jdbc.properties文件中 username属性

@Value("${username}")
private String username;

3. 使用加密的属性文件

一般的项目中,即使是 jdbc的配置文件 也不会使用明文密码,防止被别人使用,毕竟越少人知道越好。这时候使用加密的属性文件就很nice了。

PropertyPlaceholderConfigurer本身不支持 加密 但是你可以扩展该类,重写convertProperty方法

public class EncryptPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {
    @Override
    protected String convertProperty(String propertyName, String propertyValue){
        //此处可加密
    }
}
//配置
<bean class="...EncryptPropertyPlaceholderConfigurer" 
    p:locations=""
    p:filEncoding="utf-8"/>
//重写的这个方法是 PropertyResourceConfigurer 的方法
PropertyPlaceholderConfigurer ->实现了 PlaceholderConfigurerSupport ->实现了 PropertyResourceConfigurer

此处不表明加密的具体方法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值