JavaWeb-13-Spring与普通的javaweb项目整合

Spring和JavaWeb整合使用理论的步骤;

1)、Spring来控制事务(dao--JdbcTemplate)

2)、所有的组件Autowired;

3)、管理数据库。。。

 

Spring与JavaWeb整合实际的步骤;

1:导包:将aop,ioc,jdbcTemplate,事务管理等的包导入,还有spring的web包;

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>5.2.6.RELEASE</version>
</dependency>

2:写配置

 1)、将所有组件加入容器中,并能正确获取

               @Controller:servlet层;目前不能标注在servlet层;

               @Service:业务逻辑层

               @Repository:dao层

               @Component:其他组件

     2)、每个组件之间自动装配;

     3)、配置出声明式事务;

               事务管理器控制数据库连接池;

3:因为Controller层的servlet邮Tomcat管理,所以不能加入容器;如果我们在servlet层手动启动容器,那么就没办法管理容器中组件的声明周期;

因此,spring和web整合后,可以在web.xml中注册监听器,接管容器

<!-- needed for ContextLoaderListener -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <!--这是spring的配置文件位置-->
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <!-- Bootstraps the root web application context before servlet initialization -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

这个监听器创建好的ioc容器在ContextLoader类中

利用这句来获取容器

WebApplicationContext ioc = ContextLoader.getCurrentWebApplicationContext();

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章