在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 这两个配置文件。
参考:
http://blog.csdn.net/yaerfeng/article/details/25368447
http://snowolf.iteye.com/blog/588351
http://www.tuicool.com/articles/M3MVr2
http://blog.csdn.net/jiaobuchong/article/details/50530027