Java-Spring集成Web环境
Spring集成Web环境
1.Spring继承junit
原始问题:在测试类中,每个测试方法都有以下两行代码:
1 | ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml"); |
这两行代码的作用是获取容器,如果不写的话直接会提示空指针异常,所以又不能轻易删掉。
但是,一个项目下会有多个测试类,每个测试类都需要执行这两行代码,这就存在大量重复工作,因此,可以用Spring继承junit,让SpringJunit来创建Spring容器
集成步骤:
- 导入Spring集成junit的坐标
- 使用@Runwith注解替换原来的运行期
- 使用@ContextConfiguration指定配置文件或配置类
- 使用@Autowired注入需要测试的对象
- 创建测试方法进行测试
首先导入Springjunit坐标
1 | <dependency> |
然后添加注解:
2.Spring继承web
一个web包下会有多个servlet业务,每个业务使用前都需要写这两行代码来获取app对象,这就存在大量重复工作,因此,可以用Spring继承web,让SpringWeb来创建Spring容器
但是,如何让多个servlet都只共享一个spring创建呢,
当然,我们可以将创建spring的两行代码修饰为静态,
不过,现在我们采用Lisenter(监听器)的技术。
我们可以创建一个监听器类,里边进行spring的创建,每次加载项目时该类就被执行了,spring最开始就被创建,之后的servlet都只共享这一个spring了。
可以手动创造,但spring提供了相关方法。
配置文件:
1 | 首先,导入Springweb坐标: |
Spring集成web环境步骤
1.配置ContextLoaderListener监听器
2.使用WebApplicationContextUtils获得应用上下文。
3.具体方法:
- 在Web项目中,可以使用ServletContextListener监听Web应用的启动,我们可以在Web应用启动时,就加载Spring的配置文件,创建应用上下文对象ApplicationContext,再将其存储到最大域ServletContext域中,这样就可以在任意位置从域中获得应用上下文ApplicationContext对象。
web中使用:
1 | Servlet中的doGet方法: |
All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
Comment
ValineDisqus