1. 程式人生 > 實用技巧 >JavaWeb學習:Spring入門

JavaWeb學習:Spring入門

一、概述

  Spring是一個分層的SE/EE一站式輕量級開源框架

  一站式框架:有EE開發的每一層解決方案。

    Web層:SpringMVC

    Service層:Spring的Bean管理,Spring宣告式事務

    DAO層:Spring的JDBC模板,Spring的ORM模板

二、Spring的優勢、

  1、方便解耦,簡化開發

    通過Spring提供的IOC容器,可以將物件之間依賴關係交由Spring控制,以降低程式過度耦合。

  2、AOP程式設計的支援

  3、宣告式事務的支援

  4、方便整合各種優秀框架

三、IOC:Inversion of Control(控制反轉)

  耦合比如:

Class Service{ 
    public void method(){ 
        DAO dao = new DAOImpl();
        dao.method();
    }
}    

  現在DAOImpl要換成DAOExtendImpl的話,就需要修改程式碼

Class Service{ 
    public void method(){ 
        DAO dao = new DAOExtendImpl();
        dao.method();
    }
} 

  這樣就會大大增加開發風險和成本。那能不能不修改程式碼情況下就能實現程式的擴充套件?

  傳統解決方案:使用工廠模式

實現Service與Dao之間的解耦,但是DAO與工廠有耦合,解決他們之間的耦合就使用配置檔案,配置物件型別,通過反射建立物件。

  Spring的解耦底層原理也是這樣的,Spring已經提供了工廠,所以我們只需要配置物件型別就可以了。具體使用方式:

  ①、下載Spring的開發包

    https://repo.spring.io/webapp/#/artifacts/browse/tree/General/libs-release-local

    

    在springframework下找到spring,並展開,選擇要下載的版本,展開它

    

  ②、解壓

    

    docs:Spring的開發規範和API

    libs:Spring的開發jar和原始碼

    schema:Spring的配置檔案的約束

  ③、建立web專案,搭建環境

    

       

  ④、建立介面和實現類

public interface UserDAO {
    public void save();
}
public class UserDAOImpl implements UserDAO{

    @Override
    public void save() {
    System.out.println("DemoDAOImpl...");
    }
}

  ⑤、將實現類交給Spring管理

    Ⅰ、在src下新建applicationContext.xml

      在spring的解壓路徑下找到spring-framework-4.2.4.RELEASE\docs\spring-framework-reference\html\xsd-configuration.html,並雙擊開啟,找到 the beans schema,複製如下內容

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    

</beans>

    Ⅱ、將UserDAO實現類配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    <bean id="userDAO" class="com.xxx.spring.demo.UserDAOImpl"></bean>

</beans>

  ⑥、編寫測試類

    @Test
    public void demo1() {
    // 建立Spring的工廠
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    // 根據工廠獲取物件
    UserDAO userDAO = (UserDAO) applicationContext.getBean("userDAO");
    userDAO.save();
    }