SpringMVC中如何读取配置文件中的值

本文介绍了在SpringMVC中如何在测试类和Controller中读取配置文件中的值。当存在多个配置文件时,可能出现加载冲突导致属性替换错误。问题源于Spring容器仅允许一个PropertyPlaceholderConfigurer或<context:property-placeholder>,导致后续的配置被忽略。解决方案是将属性文件加载集中在一处,避免模块间冲突。
摘要由CSDN通过智能技术生成

第一种情况是在测试类中读取配置文件中的值,实现如下:

1、在spring-mybatis配置文件中引入配置文件,代码如下:

<span style="font-family:Comic Sans MS;">        <!-- 引入配置文件 -->
	<bean id="prpertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath:jdbc.properties</value>
			</list>
		</property>
	</bean></span>

2、为了让controller读取到配置文件,仍需要在spring.xml文件中引入配置文件

<span style="font-family:Comic Sans MS;"><context:property-placeholder location="classpath:jdbc.properties" /></span>

3、在测试类中写成如下形式:

<span style="font-family:Comic Sans MS;">@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:spring-mybatis.xml","classpath:spring.xml"})
public class TestMyBatis{
	//这是对应配置文件中的变量,给变量注入值
	@Value("${picUrl}")
	private String picUrl;
	。。。。。。</span>

这样便自动将配置文件中picUrl变量的值注入给了picUrl,可以测试打印输出其值,发现就是配置文件中的值。


第二种情况是在Controller中读取配置文件中的值

之前我写了两个配置文件,想同时加载,但是发现一直出现各种问题。原来在spring.xml文件中写两个这样的:

<span style="font-family:Comic Sans MS;">         <context:property-placeholder location="classpath:jdbc.properties" />
	<context:property-placeholder location="classpath:picPath.properties"/></span>
这样是行不通的。

后来我将这两个配置文件的内容合并,保存在了jdbc.properties中,便可以在Controller利用@Value对属性值进行注入了。

看看我的Controller类的写法:

<spa
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值