Spring通过xml文件配置bean,并注入properties文件中的参数

因维护老项目,需在Spring的xml中维护bean,并将配置文件中的参数注入到相应bean。此博客以Web项目为例,介绍将config.properties文件中的gatewayUrl参数注入到applicationContext.xml配置的Bean(com.pro.util.CodeManageUtil)中的方法。

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

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>

 
 
运行项目 ,你会发现完成注入……
 
 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值