如何去取ContextConfiguration

本文介绍了在Spring框架中如何通过不同方式配置测试上下文来获取Bean的方法,包括使用注解和XmlBeanFactory,并展示了多种配置文件加载的例子。

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

我们平时写test去测试Spring一起的程序时,一般都要加载context,然后再取bean之类。

写法如下:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/services-test-config.xml"})
public class MySericeTest {

@Autowired
MyService service;
...

}


现在的问题是,我要获取一个bean,但是上面这种通过annotation申明xml配置文件的方式,和我们原来的那种(如下),那光光写在annotation,那我怎么通过context的reference去获取bean呢?


[b]解决办法[/b]
其实申明一个context的成员变量,autowired一下就ok了
@Autowired
ApplicationContext context;



package com.test;

import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;

public class SpringMain {

/**
* @param args
*/
public static void main(String[] args) {
SpringBean bean = null;
XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
bean = (SpringBean)factory.getBean("test1");
bean.sayHello();

ApplicationContext act = new ClassPathXmlApplicationContext("applicationContext.xml");
bean = (SpringBean)act.getBean("test1");
bean.sayHello();

factory = new XmlBeanFactory(new FileSystemResource("F:\\ccc\\workspace_zuhe\\Test\\src\\applicationContext.xml"));
bean = (SpringBean)factory.getBean("test1");
bean.sayHello();
}

}



--------------------------------------

如果有多个xml的配置文件:
@ContextConfiguration(locations = {"classpath:com/xxx/aaa/applicationContext.xml",
"classpath:com/xxx/aaa/common-config.xml",
"classpath:com/xxx/aaa/applicationContext-dao.xml",})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值