Spring通过xml文件配置bean,并注入properties文件中的参数
1、说明
因为对开发者更加友好便利,目前大多数项目都开始使用SpringBoot的技术。最近在维护一个老项目时用到了spring,
需要在xml 中维护bean,并且需要把配置文件中的参数,注入到相应的bean中。所以才有了该篇博文,特此记录。
2、项目结构
维护的是一个Web 项目,config.properties 为记录参数的配置文件
config.properties 所记录的参数 gatewayUrl,该参数需要注入到bean中。
3、需要通过xml 配置的 Bean
package com.pro.util;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.fastjson.JSON;
/**
* @description:
* @date 2019/6/14 14:17
*/
public class CodeManageUtil {
private static final Logger logger = Logger.getLogger(CodeManageUtil.class);
/** 统一网关地址 */
private String gatewayUrl;
public String getGatewayUrl() {
return gatewayUrl;
}
public void setGatewayUrl(String gatewayUrl) {
this.gatewayUrl = gatewayUrl;
};
}
4、xml 文件中的配置
applicationContext.xml 中配置 Bean(com.pro.util.CodeManageUtil),并注入
config.properties 文件中的参数gatewayUrl 。需要在 applicationContext.xml 文件中添
加以下代码:
<!-- spring的属性加载器,加载properties文件中的属性 -->
<bean id="configPropertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<!-- <value>/WEB-INF/configInfo.properties</value> -->
<value>classpath:config.properties</value>
</property>
</bean>
<bean id="codeManageUtil" class="com.pro.util.CodeManageUtil">
<property name="gatewayUrl">
<value>${gatewayUrl}</value>
</property>
</bean>
运行项目 ,你会发现完成注入……