Spring整合web开发(6)

正常整合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测试:


猜你喜欢

转载自blog.51cto.com/4534309/2107879