Spring PropertyResolver 占位符解析(一)API 介绍

Spring 系列目录(https://www.cnblogs.com/binarylei/p/10198698.html)

Spring 3.1 提供了新的占位符解析器 PropertyResolver,默认实现为 PropertySourcesPropertyResolver。相关文章如下:

  1. Spring PropertyResolver 占位符解析(一)API 介绍
  2. Spring PropertyResolver 占位符解析(二)源码分析

一、PropertyResolver API

PropertyResolver 的默认实现是 PropertySourcesPropertyResolver,Environment 实际上也是委托 PropertySourcesPropertyResolver 完成 占位符的解析和类型转换。 类型转换又是委托 ConversionService 完成的。

public interface PropertyResolver {
// 1. contains
boolean containsProperty(String key); // 2.1 获取指定 key,不存在可以指定默认值,也可以抛出异常
String getProperty(String key);
String getProperty(String key, String defaultValue); // 2.2 类型转换,委托 ConversionService 完成
<T> T getProperty(String key, Class<T> targetType);
<T> T getProperty(String key, Class<T> targetType, T defaultValue); String getRequiredProperty(String key) throws IllegalStateException;
<T> T getRequiredProperty(String key, Class<T> targetType) throws IllegalStateException; // 3. 解析占位符 ${key}
String resolvePlaceholders(String text);
String resolveRequiredPlaceholders(String text) throws IllegalArgumentException;
}

PropertyResolver 组件完成了两件事:一是占位符解析 ${key};二是类型转换。使用方法如下:

@Test
public void PropertyResolverTest() {
PropertySource propertySource = new MapPropertySource("source",
Collections.singletonMap("name", "binarylei"));
MutablePropertySources propertySources = new MutablePropertySources();
propertySources.addFirst(propertySource);
PropertyResolver propertyResolver = new PropertySourcesPropertyResolver(propertySources); Assert.assertEquals("binarylei", propertyResolver.getProperty("name"));
Assert.assertEquals("name is binarylei", propertyResolver.resolvePlaceholders("name is ${name}"));
}

二、Spring 是如何使用的

(1) xml 配置

<context:property-placeholder
location="属性文件,多个之间逗号分隔"
file-encoding="文件编码"
ignore-resource-not-found="是否忽略找不到的属性文件"
ignore-unresolvable="是否忽略解析不到的属性,如果不忽略,找不到将抛出异常"
properties-ref="本地Properties配置"
local-override="是否本地覆盖模式,即如果true,那么properties-ref的属性将覆盖location加载的属性,否则相反"
system-properties-mode="系统属性模式,默认ENVIRONMENT(表示先找ENVIRONMENT,再找properties-ref/location的),NEVER:表示永远不用ENVIRONMENT的,OVERRIDE类似于ENVIRONMENT"
order="顺序"
/>
  • location:表示属性文件位置,多个之间通过如逗号/分号等分隔;
  • file-encoding:文件编码;
  • ignore-resource-not-found:如果属性文件找不到,是否忽略,默认 false,即不忽略,找不到将抛出异常
  • ignore-unresolvable:是否忽略解析不到的属性,如果不忽略,找不到将抛出异常
  • properties-ref:本地 java.util.Properties 配置
  • local-override:是否本地覆盖模式,即如果 true,那么 properties-ref 的属性将覆盖 location 加载的属性
  • system-properties-mode:系统属性模式,ENVIRONMENT(默认),NEVER,OVERRIDE
    1. ENVIRONMENT:将使用 Spring 3.1 提供的 PropertySourcesPlaceholderConfigurer,其他情况使用 Spring 3.1 之前的 PropertyPlaceholderConfigurer。如果是本地覆盖模式:那么查找顺序是:properties-ref、location、environment,否则正好反过来;
    2. OVERRIDE: PropertyPlaceholderConfigurer 使用,因为在 spring 3.1 之前版本是没有 Enviroment 的,所以 OVERRIDE 是 spring 3.1 之前版本的 Environment。如果是本地覆盖模式:那么查找顺序是:properties-ref、location、System.getProperty(), System.getenv(),否则正好反过来;
    3. NEVER:只查找 properties-ref、location;
  • order:当配置多个context:property-placeholder/时的查找顺序,关于顺序问题请参考:<http://www.iteye.com/topic/1131688 >

(2) 注解配置

@Configuration
@PropertySource(value = "classpath:resources.properties", ignoreResourceNotFound = false)
public class AppConfig {
// 如果想进行 Bean 属性的占位符替换,需要注册 PropertySourcesPlaceholderConfigurer
@Bean
public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}

如上配置等价于 XML 中的 context:property-placeholder/ 配置。

(3) 占位符替换

使用 Environment 属性替换,如:

<context:property-placeholder location="classpath:${env}/resources.properties"/>
<context:component-scan base-package="com.sishuok.${package}"/>
<import resource="classpath:${env}/ctx.xml"/>

同样可以在注解中使用占位符。

@PropertySource(value = "classpath:${env}/resources.properties")
@ComponentScan(basePackages = "com.sishuok.${package}")
@ImportResource(value = {"classpath:${env}/cfg.xml"})
@Value("${env}")
new ClassPathXmlApplicationContext("classpath:${env}/cfg.xml")

参考:

  1. 《pring3.1新属性管理API:PropertySource、Environment、Profile》:https://jinnianshilongnian.iteye.com/blog/2000183

每天用心记录一点点。内容也许不重要,但习惯很重要!

Spring PropertyResolver 占位符解析(一)API 介绍的更多相关文章

  1. Spring PropertyResolver 占位符解析(二)源码分析

    Spring PropertyResolver 占位符解析(二)源码分析 Spring 系列目录(https://www.cnblogs.com/binarylei/p/10198698.html) ...

  2. spring源码解析(一)---占位符解析替换

    一.结构类图 ①.PropertyResolver : Environment的顶层接口,主要提供属性检索和解析带占位符的文本.bean.xml配置中的所有占位符例如${}都由它解析 ②.Config ...

  3. spring占位符解析器---PropertyPlaceholderHelper

    一.PropertyPlaceholderHelper 职责 扮演者占位符解析器的角色,专门用来负责解析路劲中or名字中的占位符的字符,并替换上具体的值 二.例子 public class Prope ...

  4. Spring源码解析之PropertyPlaceholderHelper(占位符解析器)

    Spring源码解析之PropertyPlaceholderHelper(占位符解析器) https://blog.csdn.net/weixin_39471249/article/details/7 ...

  5. SpringBoot环境属性占位符解析和类型转换

    前提 前面写过一篇关于Environment属性加载的源码分析和扩展,里面提到属性的占位符解析和类型转换是相对复杂的,这篇文章就是要分析和解读这两个复杂的问题.关于这两个问题,选用一个比较复杂的参数处 ...

  6. 【mybatis源码学习】mybtias基础组件-占位符解析器

    一.占位符解析器源码 1.占位符解析器实现的目标 通过解析字符串中指定前后缀中的字符,并完成相应的功能. 在mybtias中的应用,主要是为了解析Mapper的xml中的sql语句#{}中的内容,识别 ...

  7. Spring属性占位符 PropertyPlaceholderConfigurer

    http://www.cnblogs.com/yl2755/archive/2012/05/06/2486752.html PropertyPlaceholderConfigurer是个bean工厂后 ...

  8. Spring PropertyPlaceholderConfigurer占位符用法

    1.PropertyPlaceholderConfigurer是一个bean工厂后置处理器的实现,也就是BeanFactoryPostProcessor接口的一个实现.PropertyPlacehol ...

  9. spring boot ${}占位符不起作用

    问题:在 pom.xml 文件里定义好属性标签,然后在 properties或者xml 中使用${key}引用,打包之后就会自动替换掉. 但是在使用 spring boot 后发现,@可以替换,但是$ ...

随机推荐

  1. java工程师基础笔试题(一)-参考答案

    一.选择和填空  (不定项哦!) 1,如下是一份文件名为Test2.java的源文件,请问,编译该文件之后会生成几份字节码文件 class Test{ class Inner{} static cla ...

  2. shell脚本-删除当天日期前3个月的数据表

    #!/bin/bash #author:skycheng #get current date string datestr=`date +'%Y-%m-%d'` start_time=`date +' ...

  3. datetime空值设置

    Cause: com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect datetime value: '' for column ...

  4. U3D框架—单例框架

    写程序应遵循的原则:高内聚(内容的聚合),低耦合(功能与功能之间的联系) 代码里尽量不要有冗余:既重复,没有用的代码 using System.Collections; using System.Co ...

  5. java 反编译工具

    (1)点击进入>>   https://jingyan.baidu.com/article/3f16e003c857082590c1036f.html (备注:如果以上链接的资源不能下载, ...

  6. spring-mvc.xml 和 application-context.xml的区别

    转自:https://www.cnblogs.com/binlin1987/p/7053016.html application-context.xml是全局的,应用于多个serverlet,配合li ...

  7. ACM-ICPC 2018 南京赛区网络预赛 G. Lpl and Energy-saving Lamps(二分+线段树区间最小)

    During tea-drinking, princess, amongst other things, asked why has such a good-natured and cute Drag ...

  8. GridView创建菜单栏

    GridView(网格视图)可以用来做九宫图.表格(行列)的视图,因其是网格状的,不用去调整权重,而且单个item可以自定义,因此也可以用来创建菜单栏(图标加文字形式),布局就一个GridView. ...

  9. how2j网站前端项目——天猫前端(第一次)学习笔记8

    其他页面的学习 这些页面有1.查询结果页 2.支付页面 3.支付成功页面 4.确认收货页面上 5.确认收货页面下 6.收获成功页面 7.评价页面上 8.评价页面下 9.登陆页面 10.注册页面 1.查 ...

  10. ecplise自动提示失效,使用补全自动提示快捷键(Alt+/),但只显示“No Default Proposals”

    在这里设置了自动提示,但是在使用的时候自动提示实现了.甚至使用补全自动提示快捷键(Alt+/),只显示“No Default Proposals”.今天在网上搜索了一下结果,主要有一下几种方法: 1. ...