正常整合 Servlet 和 Spring 没有问题的
但是每次执行 Servlet 的时候加载 Spring 配置, 加载 Spring 环境.
解决办法: 在 Servlet 的 init 方法中加载 Spring 配置文件?
当前这个 Servlet 可以使用, 但是其他的 Servlet 的用不了了!!!
将加载的信息内容放到 ServletContext 中. ServletContext 对象时全局的对象. 服务器启动的时候创建的. 在创建 ServletContext 的时候就加载 Spring 的环境.
ServletContextListener: 用于监听 ServletContext 对象的创建和销毁的.
导入; spring-web-3.2.0.RELEASE.jar
在 web.xml 中配置:
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>classpath:applicationContext.xml</param-value>
- </context-param>
修改程序的代码:
- WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
- WebApplicationContext applicationContext = (WebApplicationContext) getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
Spring 集成 JUnit 测试
1. 程序中有 Junit 环境.
2. 导入一个 jar 包. spring 与 junit 整合 jar 包.
spring-test-3.2.0.RELEASE.jar
3. 测试代码:
- @RunWith(SpringJUnit4ClassRunner.class)
- @ContextConfiguration(locations="classpath:applicationContext.xml")
- public class SpringTest {
- @Autowired
- private UserService userService;
- @Test
- public void demo1(){
- userService.sayHello();
- }
- }
(1)到 (6) 总结
Struts2:
Hibernate: 知识点比较多.
Spring:AOP. 面向切面的思想.
Spring 框架 IOC. AOP . 数据访问 . 集成 . Web
IOC: 控制反转. 将对象的创建权交给 Spring.
DI: 依赖注入. DI 需要有 IOC 环境的, DI 在创建对象的时候, 将对象的依赖的属性, 一并注入到类中
IOC 装配 Bean:(XML)
<bean id=""class=""/>
配置 Bean 其他的属性:
init-method destroy-method scope
DI 注入属性:
普通属性:
<property name="属性名" value="属性值">
对象属性:
<property name="属性名" ref="其他类的 id 或 name">
集合属性的注入:
IOC 装配 Bean:(注解)
@Component 描述 Spring 框架中 Bean
@Repository 用于对 DAO 实现类进行标注
@Service 用于对 Service 实现类进行标注
@Controller 用于对 Controller 实现类进行标注
DI 属性注入
普通属性:
@Value
对象属性:
- AutoWired
- Resource
Bean 的生命周期:
后处理 Bean.BeanPostProcessor 类.
Spring 整合 Web 项目:
Spring 整合 Junit 测试:
Spring 整合 web 开发(6)
来源: http://www.bubuko.com/infodetail-2575186.html