启动spring容器
XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
GreetingService greetingService = (GreetingService)factory.getBean("greetingService");
greetingService.sayGreeting();
//销毁容器中的所有bean
factory.destroySingletons();
用Junit测试spring 获取ApplicationContext 总的来说有两种方式:
1. 硬编码获取ApplicationContext, 其中还包括5中方式
(转载自http://blog.163.com/wjf_j2ee2009/blog/static/1326020002010460395919/)
a. 利用ClassPathXmlApplicationContext,可以从classpath中读取XML文件
- //读取一个文件
- ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
- UserDao userDao = (UserDao)context.getBean("userDao");
- //读取多个文件
- ClassPathXmlApplicationContext resource = new ClassPathXmlApplicationContext(new String[]
- {"applicationContext-ibatis-oracle.xml","applicationContext.xml","applicationContext-data-oracle.xml"});
- BeanFactory factory = resource;
- UserDao userDao = (UserDao) factory.getBean("userDao");
b. 利用ClassPathResource,可以从classpath中读取XML文件
- Resource cr = new ClassPathResource("applicationContext.xml");
- BeanFactory bf=new XmlBeanFactory(cr);
- UserDao userDao = (UserDao)bf.getBean("userDao");
c. 利用XmlWebApplicationContext读取
- XmlWebApplicationContext ctx = new XmlWebApplicationContext();
- ctx.setConfigLocations(new String[] {"/WEB-INF/ applicationContext.xml");
- ctx.setServletContext(pageContext.getServletContext());
- ctx.refresh();
- UserDao userDao = (UserDao ) ctx.getBean("userDao ");
d. 利用FileSystemResource读取
- Resource rs = new FileSystemResource("D:/tomcat/webapps/test/WEB-INF/classes/ applicationContext.xml");
- BeanFactory factory = new XmlBeanFactory(rs);
- UserDao userDao = (UserDao )factory.getBean("userDao");
注意:利用FileSystemResource,则配置文件必须放在project直接目录下,或者写明绝对路径,否则就会抛出找不到文件的异常
e. 利用FileSystemXmlApplicationContext读取,可以指定XML定义文件的相对路径或者绝对路径来读取定义文件。
- String[] path={"WebRoot/WEB-INF/applicationContext.xml","WebRoot/WEB-INF/applicationContext_task.xml"};
- ApplicationContext context = new FileSystemXmlApplicationContext(path);
- String path="WebRoot/WEB-INF/applicationContext*.xml";
- ApplicationContext context = new FileSystemXmlApplicationContext(path);
- ApplicationContext ctx = new FileSystemXmlApplicationContext("classpath:地址");
2.采用Spring 提供的Test框架, 需要下载Spring-test jar包,采用注释的方式
@RunWith(SpringJUnit4ClassRunner.class)
- //@ContextConfiguration({"file:src/main/webapp/WEB-INF/spring/applicationContext.xml"})
- @ContextConfiguration("classpath:applicationContext.xml")
文件和classpath都可以,但这只完成自动注入功能,如需要获取ApplicationContext, 需要继承ApplicationContextAware接口,实现setApplicationContext方法,在该方法就可以获取ApplicationContext
- @Override
- public void setApplicationContext(ApplicationContext arg0)
- throws BeansException {
- context=arg0;
- }
之后就可以使用context.
注意:两种方式不能混用,否则会开启两个spring容器。推荐使用第二种。

浙公网安备 33010602011771号