第一种情况是在测试类中读取配置文件中的值,实现如下:
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