Spring 注解学习手札(六) 测试

本文介绍如何在Spring3中使用@Value注解来获取properties文件中的配置值,并展示了如何在测试类中通过@ContextConfiguration注解指定Spring配置文件的位置。
Spring 3支持@value注解的方式获取properties文件中的配置值

在bean中使用@value注解获取配置文件的值

@ContextConfiguration(locations={"classpath:/applicationContext.xml"},inheritLocations=true)
public class SpringDI extends AbstractJUnit4SpringContextTests {

@Autowired
private SearchClient searchClient;

@Autowired
private HttpSearchClient httpSearchClient;

@Autowired
private CloudSearchClient cloudSearchClient;

@Value("${solr.http.url}")
private String httpUrl;

@Value("${solr.zk.url}")
private String zkHost;

@Value("${solr.zk.collection}")
private String collection;


@Test
public void testGetBean() {
HttpSearchClient httpSearchClientBySearchClient = searchClient.createHttpSearchClient(httpUrl);
CloudSearchClient cloudSearchClientBySearchClient = searchClient.createCloudSearchClient(zkHost, collection);
}
}


在 ① 处,标注了一个类级的 @ContextConfiguration 注解,这里 Spring 将按 TestContext 契约查找 classpath:/com/baobaotao/service/TestUserService-context.xml 的 Spring 配置文件,并使用该配置文件启动 Spring 容器。@ContextConfiguration 注解有以下两个常用的属性:
locations:可以通过该属性手工指定 Spring 配置文件所在的位置,可以指定一个或多个 Spring 配置文件。如下所示:
@ContextConfiguration(locations={“xx/yy/beans1.xml”,” xx/yy/beans2.xml”})
inheritLocations:是否要继承父测试用例类中的 Spring 配置文件,默认为 true。如下面的例子:
@ContextConfiguration(locations={"base-context.xml"})  
public class BaseTest {
// ...
}
@ContextConfiguration(locations={"extended-context.xml"})
public class ExtendedTest extends BaseTest {
// ...
}


如果 inheritLocations 设置为 false,则 ExtendedTest 仅会使用 extended-context.xml 配置文件,否则将使用 base-context.xml 和 extended-context.xml 这两个配置文件。

[img]https://img-blog.youkuaiyun.com/20140228165709328?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvaGVoZXhpYW95b3U=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast[/img]

参考:
http://blog.youkuaiyun.com/yaerfeng/article/details/25368447
http://snowolf.iteye.com/blog/588351
http://www.tuicool.com/articles/M3MVr2
http://blog.youkuaiyun.com/jiaobuchong/article/details/50530027
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值