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();

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

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