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

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

Spring 系列目录(https://www.cnblogs.com/binarylei/p/10117436.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:当配置多个

(2) 注解配置

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

如上配置等价于 XML 中的

(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


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

原文地址:https://www.cnblogs.com/binarylei/p/10284826.html

时间: 2024-08-23 09:18:13

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

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

一.结构类图 ①.PropertyResolver : Environment的顶层接口,主要提供属性检索和解析带占位符的文本.bean.xml配置中的所有占位符例如${}都由它解析 ②.ConfigurablePropertyResolver : 该接口定义了如何对组件本身进行配置.如:刚刚提到获取value时可以指定任意类型,这依赖于ConversionService进行类型转换,当前接口就提供了对ConversionService的设置和获取.另外,可以配置属性占位符的格式,包括:占位符前

spring占位符解析器---PropertyPlaceholderHelper

一.PropertyPlaceholderHelper 职责 扮演者占位符解析器的角色,专门用来负责解析路劲中or名字中的占位符的字符,并替换上具体的值 二.例子 public class PropertyPlaceholderHelperDemo { @SuppressWarnings("resource") public static void main(String[] args) { Properties properties = System.getProperties();

占位符解析

占位符解析过程 占位符解析器 /** * 从指定的属性源中,将占位符解析为具体的值 */ public class PropertyPlaceholderHelper { private static final Log logger = LogFactory.getLog(PropertyPlaceholderHelper.class); private static final Map<String, String> wellKnownSimplePrefixes = new HashMa

Spring属性占位符 PropertyPlaceholderConfigurer

http://www.cnblogs.com/yl2755/archive/2012/05/06/2486752.html PropertyPlaceholderConfigurer是个bean工厂后置处理器的实现,也就是BeanFactoryPostProcessor接口的一个实现.PropertyPlaceholderConfigurer可以将上下文(配置文件)中的属性值放在另一个单独的标准java Properties文件中去.在XML文件中用${key}替换指定的properties文件

Spring属性占位符PropertyPlaceholderConfigurer的使用

1.一个简单的Demo 1.1.创建conf.xml <?xml version="1.0" encoding="UTF-8"?><!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"><beans>    <bean id="

Spring源码深度解析pdf

下载地址:网盘下载 <Spring源码深度解析>从核心实现和企业应用两个方面,由浅入深.由易到难地对Spring源码展开了系统的讲解,包括Spring的设计理念和整体架构.容器的基本实现.默认标签的解析.自定义标签的解析.bean的加载.容器的功能扩展.AOP.数据库连接JDBC.整合MyBatis.事务.SpringMVC.远程服务.Spring消息服务等内容. <Spring源码深度解析>不仅介绍了使用Spring框架开发项目必须掌握的核心概念,还指导读者如何使用Spring框

SPRING多个占位符配置文件解析源码研究--转

原文地址:http://www.cnphp6.com/archives/85639 Spring配置文件: <context:property-placeholder location="classpath:/settings.properties" /> <context:property-placeholder location="classpath:/conf.properties"/> settings.properties redi

【Spring源码分析】.properties文件读取及占位符${...}替换源码解析

前言 我们在开发中常遇到一种场景,Bean里面有一些参数是比较固定的,这种时候通常会采用配置的方式,将这些参数配置在.properties文件中,然后在Bean实例化的时候通过Spring将这些.properties文件中配置的参数使用占位符"${}"替换的方式读入并设置到Bean的相应参数中. 这种做法最典型的就是JDBC的配置,本文就来研究一下.properties文件读取及占位符"${}"替换的源码,首先从代码入手,定义一个DataSource,模拟一下JDB

spring加载配置文件无法解析占位符问题:Could not resolve placeholder &#39;from&#39; in string value &quot;${from}&quot;

Could not resolve placeholder 'from' in string value "${from}" 解决: 在spring的xml配置文件中当有多个*.properties文件需要加载时, 应当集中在一个xml文件中加载,建议在主xml文件中加载,即(applicationContext.xml)中加载, 这样就不需要关注 子xml文件 与 *.properties 加载顺序问题 加载多个*.properties文件,以','隔开 <context:pr