Spring context:property-placeholder元素详解

本文将介绍在Spring中,怎样引用外部属性文件(properties)中的值。在Spring配置文件中使用${}进行引用,也可以在代码中使用@Value("${}")注解进行引用。在使用前,我们需要配置PropertyPlaceholderConfigurer Bean或者配置context:property-placeholder元素。

在进行项目开发中,我们需要维护一些常量,这些常量在不同的环境下面是不一样的,例如:数据库信息,在开发库、测试库和正式库中数据库URL地址和用户名/密码可能不一样,我们不能直接将这些信息写入到代码中,因为写入到代码中我们每次都需要修改代码,然后重新编译代码。这是麻烦的!!!再Spring中,可以使用properties文件进行维护,然后在代码中使用注解@Value进行引用,也可以在Spring的配置文件中使用${}进行引用。

但是,在进行引用之前,我们需要通过配置 PropertyPlaceholderConfigurer Bean或者使用<context:property-placeholder>标签进行配置。

实例:假如我们需要在项目中引入数据库,将数据库信息保存到jdbc.properties文件中,jdbc.properties内容如下:

#jdbc配置
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=root

配置PropertyPlaceholderConfigurer Bean

PropertyPlaceholderConfigurer实现了BeanFactoryPostProcessor接口,它能够对<bean/>中的属性值进行外在化管理。开发者可以提供单独的属性文件来管理相关属性。

<bean id="propertyPlaceholderConfigurer"   
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
    <property name="locations">  
        <list>  
            <value>classpath:jdbc.properties</value>  
        </list>  
    </property>  
</bean>

在 Spring 配置文件的 bean 中使用,如下代码:

<bean id="testDataSource" 
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${jdbc.driverClassName}"/>
    <property name="url" value="${jdbc.url}"/>
    <property name="username" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
</bean>

在 Java 代码中使用,代码如下:

@Service
public class JdbcInfo {
    @Value("${jdbc.driverClassName}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;
}

PropertyPlaceholderConfigurer内置的功能非常丰富,如果它未找到${xxx}中定义的xxx键,它还会去JVM系统属性(System.getProperty())和环境变量(System.getenv())中寻找。通过启用systemPropertiesMode和searchSystemEnvironment属性,开发者能够控制这一行为。

<context:property-placeholder/>元素

为简化PropertyPlaceholderConfigurer的使用,Spring提供了<context:property-placeholder/>元素。下面给出了配置示例,启用它后,开发者便不用配置PropertyPlaceholderConfigurer对象了。实例:

<context:property-placeholder location="classpath:jdbc.properties"/> 

总结

本文介绍了Spring中两种引用外部属性文件的方式,可以使应用程序可配置化。Spring提供了 PropertyPlaceholderConfigurer 和 <context:property-placeholder/> 两种方式,后者是前者的简化。

谁不会休息,谁就不会工作。 —— 列宁
2 不喜欢
说说我的看法 -
全部评论(
没有评论
关于
本网站专注于 Java、数据库(MySQL、Oracle)、Linux、软件架构及大数据等多领域技术知识分享。涵盖丰富的原创与精选技术文章,助力技术传播与交流。无论是技术新手渴望入门,还是资深开发者寻求进阶,这里都能为您提供深度见解与实用经验,让复杂编码变得轻松易懂,携手共赴技术提升新高度。如有侵权,请来信告知:hxstrive@outlook.com
其他应用
公众号