配置参数从配置文件中加载到PropertiesFactoryBean 和配置参数从数据库加载到PropertiesFactoryBean 的实现,及项目中的相关应用

本文介绍如何使用Spring框架加载.properties文件中的配置参数,并通过PropertiesFactoryBean和PropertyPlaceholderConfigurer实现配置的占位符处理。同时,展示了如何通过DatabaseConfiguration类从数据库表中加载配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.加载.properties文件中的配置参数加载到PropertiesFactoryBean容器中

<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
    <property name="locations">//本地资源 读取方式,用流读取资源进行加载。
        <list>
            <value>classpath:config.properties</value>
            <value>classpath:redis.properties</value>
        </list>
    </property>
</bean>

如此,两个properties 的属性变被放入了Spring 的PropertiesFactoryBean中

在此,有一点需要注意,如果在xml中需要用到刚刚配置的属性,我们会去用${“key”}方式去取,此时需要配置“占位符“,

<!--在xml使用properties文件中的的配置数据时,需要用到PropertyPlaceholderConfigurer做占位符-->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="properties">
            <ref bean="configProperties"/>
    </property>
</bean>

PropertyPlaceholderConfigurer会把配置的properties解析并存放为java标准的properties,此时在xml中我们可以通过${"key"}去取。

 

 

2.

<bean name="DatabaseConfigrationFactoryBean" class="com.shopManager.config.DatabaseConfigrationFactoryBean">
    <constructor-arg ref="DatabaseConfiguration"/>
</bean>

<bean name="DatabaseConfiguration" class="org.apache.commons.configuration.DatabaseConfiguration">

</bean>

/**
 * Build a configuration from a table containing multiple configurations.
 * No commits are performed by the new configuration instance.
 *
 * @param datasource    the datasource to connect to the database
 * @param table         the name of the table containing the configurations
 * @param nameColumn    the column containing the name of the configuration
 * @param keyColumn     the column containing the keys of the configuration
 * @param valueColumn   the column containing the values of the configuration
 * @param name          the name of the configuration
 */
public DatabaseConfiguration(DataSource datasource, String table, String nameColumn,
        String keyColumn, String valueColumn, String name)
{
    this(datasource, table, nameColumn, keyColumn, valueColumn, name, false);
}

从它的这个构造中我们可以发现需要传入的参数,数据源、表名、名称配置环境的名称、属性名、属性值,配置名称。(可以根据自己需要进行配置)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值