一、整合Junit
之前测试类中:
public class TestApp {
@Test
public void demo01(){
String xmlPath = "applicationContext.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
AccountService accountService = (AccountService) applicationContext.getBean("accountService");
accountService.transfer("jack", "rose", 1000);
}
}
整合后可以写为:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext.xml")
public class TestApp {
@Autowired //与junit整合,不需要在spring xml配置扫描
private AccountService accountService;
@Test
public void demo01(){
accountService.transfer("jack", "rose", 1000);
}
}
二、整合web程序
想要整合web程序,只要在服务器启动的时候将spring的配置文件加载起来就可以了(如果加载不进来,spring自然是拿不到的了)。而想在tomcat启动加载配置文件有如下三种情况:
- servlet --> init(ServletConfig) --> <load-on-startup>2
- filter --> init(FilterConfig) --> web.xml注册过滤器自动调用初始化
- listener --> ServletContextListener --> servletContext对象监听
spring使用的就是第三种,spring提供监听器 ContextLoaderListener。在web.xml文件中进行如下配置(如果只配置监听器,默认加载xml位置:/WEB-INF/applicationContext.xml):
<!-- 确定配置文件位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 配置spring 监听器,加载xml配置文件 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
之后启动服务器时,即可完成spring配置文件的加载。现在再以spring中操作数据库中的事务管理中转账案例为例,将转账业务代码在servlet中执行,即之前的:
@Test
public void demo01(){
String xmlPath = "applicationContext.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
AccountService accountService = (AccountService) applicationContext.getBean("accountService");
accountService.transfer("jack", "rose", 1000);
}
现在放在servlet中执行:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 从application作用域(ServletContext)获得spring容器
//方式1: 手动从作用域获取
ApplicationContext applicationContext =
(ApplicationContext) this.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
//方式2:通过工具获取
ApplicationContext apppApplicationContext2 =
WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
//操作
AccountService accountService = (AccountService) applicationContext.getBean("accountService");
accountService.transfer("jack", "rose", 1000);
}
那么转账业务也是可以完成的。