1. 程式人生 > 其它 >GDI繪製簡單跟蹤座標系--C#學習隨筆

GDI繪製簡單跟蹤座標系--C#學習隨筆

Spring框架介紹

1.Spring

1.1 簡介

  • 2002年,首次推出了Spring框架的雛形:interface21框架!
  • Spring框架即以interface21框架為基礎,經過重新的設計,並不斷豐富其內涵,於2004年3月24日,釋出了1.0正式版。
  • Rod Jahnson,Spring Framework創始人,著名作者,悉尼大學的博士,專業是音樂學。
  • spring理念:使現有的技術更加容易使用,本身是一個大雜燴,整合了現有的技術框架!
  • SSH:Struct2 + Spring + Hibernate
  • SSM:SpringMVC + Spring + Mybatis

官網:https://spring.io/projects/spring-framework#overview

1.2 優點:

  • Spring是一個開源的免費的框架(容器)!
  • Spring是一個輕量級的,非入侵式的框架!
  • 控制反轉(IOC),面向切面程式設計(AOP)
  • 支援事務的處理,對框架整合的支援!

總結一句話:Spring就是一個輕量級的控制反轉(IOC)和麵向切面程式設計(AOP)的框架!

弊端:發展了太久之後,違背了原來的理念!配置十分繁瑣,人稱:“配置地獄!”

1.3 組成

1.4 拓展

現代化的Java開發,說白了就是基於Spring的開發!

  • Spring Boot
    • 一個快速開發的腳手架
    • 基於SpringBoot可以快速的開發單個微服務
    • 約定大於配置
  • Spring Cloud
    • SpringCloud是基於SpringBoot實現的

2.IOC理論推導

  1. UserDao介面
  2. UserDaoImpl實現類
public interface UserDao {
   public void getUser();
}
public class UserDaoImpl implements UserDao {

    public void getUser() {
        System.out.println("預設獲取使用者的資料");
    }
}
public class UserDaoOracleImpl implements UserDao {
    public void getUser() {
        System.out.println("Oracle獲取用於資料!");
    }
}
  1. UserService業務介面
  2. UserServiceImpl業務實現類
public interface UserService {
    public void getUser();
}
  • 使用Set注入之前
  • 使用Set注入之後

在我們之前的業務中,使用者的需求可能會影響我們原來的程式碼,我們需要根據使用者的需求去修改原始碼!如果程式碼量十分大,修改一次的成本代價十分昂貴!

我們使用一個Set介面實現,已經發生了革命性的變化!

// 利用set進行實現動態值的注入!
public void setUserDao(UserDao userDao) {
    this.userDao = userDao;
}
  • 之前,程式是主動建立物件!控制權在程式設計師手上!
  • 使用Set注入後,程式不再具有主動性,而是變成了被動的接受物件!

這種思想,從本質上解決了問題,我們程式設計師不用再去管理物件的建立了。系統的耦合性大大降低,可以更加專注在業務的實現上!這是IOC的原型!

3.IOC本質

控制反轉IOC(Inversion of Control),是一種設計思想,DI(依賴注入)是實現IOC的一種方法,也有人認為Dl只是IOC的另一種說法。沒有IOC的程式中,我們使用面向物件程式設計,物件的建立與物件間的依賴關係完全硬編碼在程式中,物件的建立由程式自己控制,控制反轉後將物件的建立轉移給第三方,個人認為所謂控制反轉就是:獲得依賴物件的方式反轉了。

採用XML方式配置Bean的時候,Bean的定義資訊是和實現分離的,而採用註解的方式可以把兩者合為一體,Bean的定義資訊直接以註解的形式定義在實現類中,從而達到了零配置的目的。

控制反轉是一種通過描述(XML或註解)並通過第三方去生產或獲取特定物件的方式。在Spring中實現控制反轉的是IOC容器,其實現方法是依賴注入(Dependency Injection,DI)。

4.HelloSpring

4.1 匯入Spring相關jar包

注:spring需要匯入commons-logging進行日誌記錄,我們利用maven,它會自動下載對應的依賴項

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.8</version>
</dependency>

4.2 編寫相關程式碼

  1. 編寫一個Hello實體類

    public class Hello {
    
        private String name;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        @Override
        public String toString() {
            return "Hello{" +
                    "name='" + name + '\'' +
                    '}';
        }
    }
    
  2. 編寫spring配置檔案,這裡我們命名為beans.xml

    <?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
            https://www.springframework.org/schema/beans/spring-beans.xsd">
    
        <!--bean就是java物件,有spring建立和管理-->
        <bean id="hello" class="com.mc.pojo.Hello">
            <property name="name" value="Spring"/>
        </bean>
    
    </beans>
    
  3. 進行測試

    public class MyTest {
        public static void main(String[] args) {
            // 獲取Spring的上下文物件
            // 解析beans.xml檔案,生成管理相應的Bean物件
            ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
            // 我們的物件現在都在Spring中管理了,我們要使用,直接去裡面取出來就可以!
            // getBean:引數即為spring配置檔案中bean的id
            Hello hello = (Hello) context.getBean("hello");
            System.out.println(hello.toString());
        }
    }
    

4.3 小結

  1. 該例子設計到了Spring的三個核心:
  • 所有的類都需要裝配到bean裡面
  • 所有的bean都需要通過容器去取
  • 容器中取得的bean就是一個物件
  1. 現在只需要改動bean標籤即可建立不同物件
<bean id="mysqlImpl" class="com.mc.pojo.UserDaoMysqlImpl"/>
<bean id="oracleImpl" class="com.mc.pojo.UserDaoOracleImpl"/>

<bean id="UserServiceImpl" class="com.mc.service.UserServiceImpl">
    <!--
         ref: 引用Spring容器中建立好的物件
         value: 具體的值,基本資料型別
    -->
    <property name="userDao" ref="mysqlImpl"/>
</bean>
// 獲取ApplicationContext  拿到Spring的容器
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
// 容器在手,天下我有,需要什麼,就直接get什麼
UserServiceImpl userServiceImpl = (UserServiceImpl) context.getBean("UserServiceImpl");
userServiceImpl.getUser();
  1. 思考:
  • Hello物件是誰建立的?

    • Hello 物件是由Spring建立的
  • Hello 物件的屬性是怎麼設定的?

    • Hello 物件的屬性是由Spring容器設定的

這個過程就叫控制反轉︰

  • 控制:誰來控制物件的建立,傳統應用程式的物件是由程式本身控制建立的,使用Spring後,物件是由Spring來建立的
  • 反轉∶程式本身不建立物件,而變成被動的接收物件
  • 依賴注入:就是利用set方法來進行注入的
  • IOC是一種程式設計思想,由主動的程式設計變成被動的接收
  • 可以通過newClassPathXmlApplicationContext去瀏覽一下底層原始碼
  • OK,到了現在,我們徹底不用再程式中去改動了,要實現不同的操作,只需要在xml配置檔案中進行修改,所謂的lOC,一句話搞定:物件由Spring來建立,管理,裝配!

5.IOC建立物件的方式

5.1 預設使用無參構造建立物件

<bean id="user" class="com.mc.pojo.User">
    <property name="name" value="MC"/>
</bean>

5.2 假設我們要使用有參構造來建立物件

  • 方法一:下標賦值
<bean id="user" class="com.mc.pojo.User">
    <constructor-arg index="0" value="狂神說Java"/>
</bean>
  • 方法二:通過型別建立物件,不建議使用
<bean id="user" class="com.mc.pojo.User">
    <constructor-arg type="java.lang.String" value="qinjiang"/>
</bean>
  • 方法三:直接通過引數名建立物件
<bean id="user" class="com.mc.pojo.User">
    <constructor-arg name="name" value="狂神"/>
</bean>

總結:在配置檔案載入的時候,容器中管理的物件(bean)就已經初始化了!

6.Spring配置

6.1 別名

<!--別名,如果添加了別名,我們也可以使用別名獲取到這個物件-->
<alias name="user" alias="userNew"/>

6.2 Bean的配置

<!--
    id: bean的唯一識別符號,也就是相當於我們學的物件名
    class: bean物件所對應的全限定名:  包名 + 型別
    name: 也是別名,而且name可以同時取多個別名
-->
<bean id="userT" class="com.mc.pojo.UserT" name="userT2 u2,u3;u4">
    <property name="name" value="西部開源"/>
</bean>

6.3 import

這個import,一般用於團隊開發使用,他可以將多個配置檔案,匯入合併為一個

假設,現在專案中有多個人開發,這三個人負責不同的類開發,不同的類需要註冊在不同的bean中,我們可以利用import將所有人的beans.xml合併為一個總的!

  • 張三
  • 李四
  • 王五
  • applicationContext.xml
<import resource="beans.xml"/>
<import resource="beans2.xml"/>
<import resource="beans3.xml"/>

使用的時候,直接使用總的配置就可以了

7.依賴注入

7.1 構造器注入

之前分析過,見5.1~5.2

7.2 Set方式注入【重點】

  • 依賴注入:Set注入!
    • 依賴:bean物件的建立依賴於容器!
    • 注入:bean物件中的所有屬性,由容器來注入!

【環境搭建】

1.複雜型別

public class Address {
    private String address;

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

2.真實測試物件

public class Student {
    private String name;
    private Address address;
    private String[] books;
    private List<String> hobbys;
    private Map<String,String> card;
    private Set<String> games;
    private String wife;
    private Properties info;
}

3.beans.xml

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="student" class="com.mc.pojo.Student">
        <!--第一種,普通值注入,直接使用value-->
        <property name="name" value="秦疆"/>
    </bean>

</beans>

4.測試類

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Student student = (Student) context.getBean("student");
        System.out.println(student.getAddress());
    }
}

完善注入資訊

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="address" class="com.mc.pojo.Address">
        <property name="address" value="西安"/>
    </bean>
    <bean id="student" class="com.mc.pojo.Student">
        <!--第一種,普通值注入直接使用value-->
        <property name="name" value="秦疆"/>
        <!--第二種,bean注入,使用ref-->
        <property name="address" ref="address"/>
        <!--第三種,陣列注入,使用array-->
        <property name="books">
            <array>
                <value>紅樓夢</value>
                <value>水滸傳</value>
                <value>三國演義</value>
                <value>西遊記</value>
            </array>
        </property>
        <!--第四種,List注入,使用list-->
        <property name="hobbys">
            <list>
                <value>聽歌</value>
                <value>敲程式碼</value>
                <value>看電影</value>
            </list>
        </property>
        <!--第五種,Map注入,使用map-->
        <property name="card">
            <map>
                <entry key="身份證" value="231231231231231"/>
                <entry key="銀行卡" value="156436465231311"/>
            </map>
        </property>
        <!--第六種,Set注入,使用set-->
        <property name="games">
            <set>
                <value>LOL</value>
                <value>COC</value>
                <value>BOB</value>
            </set>
        </property>
        <!--第七種,null注入,使用null-->
        <property name="wife">
            <null/>
        </property>
        <!--第八種,Properties注入,使用props-->
        <property name="info">
            <props>
                <prop key="學號">20210812</prop>
                <prop key="姓名">小李</prop>
                <prop key="性別">男</prop>
            </props>
        </property>
    </bean>

</beans>

7.3 拓展方式注入

我們可以使用p名稱空間和c名稱空間進行注入

官方解釋:

使用!

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

    <!--p名稱空間注入,可以直接注入屬性的值:property-->
    <bean id="user" class="com.mc.pojo.User" p:name="狂神" p:age="18"/>

    <!--c名稱空間注入,通過構造器注入:construct-args-->
    <bean id="user2" class="com.mc.pojo.User" c:name="秦疆" c:age="20"/>
</beans>

測試:

@Test
public void test2(){
    ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
    User user = context.getBean("user2", User.class);
    System.out.println(user);
}

注意點:p命名和c名稱空間不能直接使用,需要匯入xml約束!

xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"

7.4 bean的作用域

  1. 單例模式(Spring預設機制)

    <bean id="user" class="com.mc.pojo.User" p:name="狂神" p:age="18" scope="singleton"/>
    
  2. 原型模式:每次從容器中get的時候,都會產生一個新物件!

    <bean id="accountService" class="com.something.DefaultAccountService" scope="prototype"/>
    
  3. 其餘的request、session、application、websocket,這些個只能在web開發中使用到!

8.Bean的自動裝配

  • 自動裝配是Spring滿足bean依賴的一種方式!
  • Spring會在上下文中自動尋找,並自動給bean裝配屬性!

在Spring中有三種自動裝配的方式

  1. 在xml中顯示的配置
  2. 在java中顯示的配置
  3. 隱式的自動裝配【重要】

8.1 測試

環境搭建:一個人有兩個寵物!

8.2 ByName自動裝配

<!--
    byName: 會自動在容器上下文中查詢和自己物件set方法後面的值對應的beanid
-->
<bean id="people" class="com.mc.pojo.People" autowire="byName">
    <property name="name" value="小狂神"/>
</bean>

8.3 ByType自動裝配

<!--
    byName: 會自動在容器上下文中查詢和自己物件set方法後面的值對應的beanid
    byType: 會自動在容器上下文中查詢和自己物件屬性型別相同的bean
-->
<bean id="people" class="com.mc.pojo.People" autowire="byType">
    <property name="name" value="小狂神"/>
</bean>

小結:

  • byName的時候,需要保證所有bean的id唯一,並且這個bean需要和自動注入的屬性的set方法的值一致!
  • byType的時候,需要保證所有bean的class唯一,並且這個bean需要和自動注入的屬性的型別一致!

8.4 使用註解實現自動裝配

jdk1.5支援的註解,Spring2.5就支援註解了!
The introduction of annotation-based configuration raised the question of whether this approach is “better" than XML.
要使用註解須知:

  1. 匯入約束:context約束
  2. 配置註解的支援:< context:annotation-config/ >【重要】
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config/>

</beans>

@Autowired

  • 直接在屬性上使用即可!也可以在set方式上使用!

  • 使用Autowired 我們可以不用編寫Set方法了,前提是你這個自動裝配的屬性在lOC (Spring)容器中存在,且符合名字byname!

科普:

@Nullable  欄位標記了這個註解,說明這個欄位可以為null
public @interface Autowired {
    boolean required() default true;
}

測試程式碼

public class People {
    @Autowired
    private Dog dog;
    // 如果顯示定義了Autowired的required屬性為false,說明這個物件可以為null,否則不允許為空
    @Autowired(required = false)
    private Cat cat;
    private String name;
}

如果@Autowired自動裝配的環境比較複雜,自動裝配無法通過一個註解【@Autowired】完成的時候,我們可以使用@Qualifier(value="xxx")去配置@Autowired的使用,指定一個唯一的bean物件注入!

public class People {
    @Autowired
    @Qualifier(value = "dog11")
    private Dog dog;
    
    @Autowired
    @Qualifier(value = "cat11")
    private Cat cat;
    private String name;
}

@Resource註解

public class People {
    @Resource
    private Dog dog;

    @Resource(name = "cat2")
    private Cat cat;
}

小結:

@Resource 和@ Autowired 的區別:

  • 都是用來自動裝配的,都可以放在屬性欄位上
  • @Autowired 通過byType的方式實現,而且必須要求這個物件存在! 【常用】
  • @Resource 預設通過byName的方式實現,如果找不到名字,則通過byType實現!如果兩個都找不到的情況下,就報錯!【常用】
  • 執行順序不同:@Autowired通過byType的方式實現。@Resource預設通過byName的方式實現。

9.使用註解開發

在Spring4之後,要使用註解開發,必須要保證aop的包匯入了

使用註解需要匯入context約束,增加註解的支援!

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

    <context:annotation-config/>

</beans>
  1. bean

  2. 屬性如何注入

    • 放在類上,說明這個類被Spring管理了,就是註冊bean
    // 等價於<bean id="user" class="com.mc.pojo.User"/>
    // @Component: 元件
    @Component
    public class User {
    
        public String name;
    
        // 相當於 <property name="name" value="小馬"/>
        @Value("小馬")
        public void setName(String name) {
            this.name = name;
        }
    }
    
  3. 衍生的註解

    @Component 有幾個衍生註解,我們在web開發中,會按照MVC三層架構分層!

    • dao 【@Repository】

    • service 【@Service】

    • controller

      這四個註解功能都是一樣的,都是代表將某個類註冊到Spring中,裝配Bean

  4. 自動裝配置

    @Autowired:自動裝配通過型別。名字
      如果Autowired不能唯一自動裝配上屬性,則需要通過@Qualifier(value="xxx")
    @Nullable欄位標記了這個註解,說明這個欄位可以為null
    @Resource:自動裝配通過名字、型別
    
  5. 作用域

    @Component
    @Scope("prototype")
    public class User {
    
        public String name;
    
        // 相當於 <property name="name" value="小馬"/>
        @Value("小馬")
        public void setName(String name) {
            this.name = name;
        }
    }
    
  6. 小結

    xml與註解:

    • xml更加萬能,適用於任何場合!維護簡單方便。

    • 註解不是自己類使用不了,維護相對複雜!

    xml與註解的最佳實踐:

    • xml用來管理bean

    • 註解只負責完成屬性的注入

    • 我們在使用的過程中,只需要注意一個問題:必須讓註解生效,就需要開啟註解的支援

    <!--指定要掃描的包,這個包下的註解就會生效-->
    <context:component-scan base-package="com.mc"/>
    <context:annotation-config/>
    

10.使用Java的方式配置Spring

我們現在要完全不使用Spring的xml配置了,全權交給Java來做!

JavaConfig 是Spring的一個子專案,在Spring 4 之後,它成為了一個核心功能!

實體類

// 這裡這個註解的意思,就是說這個類被Spring接管了,註冊到了容器中
@Component
public class User {

    public String name;

    @Value("狂神")  // 屬性注入值
    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                '}';
    }
}

配置檔案

// 這個也會被Spring容器託管,註冊到容器中,因為它本來就是一個@Component
// @Configuration代表這是一個配置類,就和我們之前的beans.xml是一樣的
@Configuration
@ComponentScan("com.mc.pojo")
@Import(MyConfig2.class)
public class MyConfig {

    // 註冊一個bean,就相當於我們之前寫的一個bean標籤
    // 這個方法的名字,就相當於bean標籤中的id屬性
    // 這個方法的返回值,就相當於bean標籤中的class屬性
    @Bean
    public User user(){
        return new User(); // 就是返回要注入到bean的物件!
    }
}

測試類

public class MyTest {
    public static void main(String[] args) {
        // 如果完全使用了配置類方法去做,我們就只能通過AnnotationConfig上下文來獲取容器,通過配置類的class物件載入!
        ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
        User getUser = (User) context.getBean("user");
        System.out.println(getUser.getName());
    }
}

這種純Java的配置方式,在SpringBoot中隨處可見!

11.代理模式

為什麼要學習代理模式?因為這就是SpringAOP的底層!【SpringAOP 和 SpringMVC】

代理模式的分類:

  • 靜態代理
  • 動態代理

11.1 靜態代理

角色分析:

  • 抽象角色︰一般會使用介面或者抽象類來解決
  • 真實角色︰被代理的角色
  • 代理角色︰代理真實角色,代理真實角色後,我們一般會做一些附屬操作
  • 客戶 :訪問代理物件的人

實現步驟:

  1. 介面

    // 租房
    public interface Rent {
        public void rent();
    }
    
  2. 真實角色

    // 房東
    public class Host implements Rent {
        public void rent() {
            System.out.println("房東要出租房子!");
        }
    }
    
  3. 代理角色

    public class Proxy implements Rent{
        private Host host;
    
        public Proxy() {
        }
    
        public Proxy(Host host) {
            this.host = host;
        }
    
        public void rent() {
            seeHouse();
            host.rent();
            hetong();
            fare();
        }
    
        // 看房
        public void seeHouse(){
            System.out.println("中介帶你看房!");
        }
    
        // 看房
        public void hetong(){
            System.out.println("籤租賃合同!");
        }
    
        // 收中介費
        public void fare(){
            System.out.println("收中介費!");
        }
    }
    
  4. 客戶端訪問代理角色

    public class Client {
        public static void main(String[] args) {
            // 房東要租房子
            Host host = new Host();
            // 代理,中介幫房東租房子,但是呢,代理角色會有一些附屬操作
            Proxy proxy = new Proxy(host);
            // 你不用面對房東,直接找中介租房即可
            proxy.rent();
        }
    }
    

代理模式的好處:

  • 可以使真實角色的操作更加純粹,不用去關注一些公共的業務
  • 公共業務就交給了代理角色,實現了業務的分工
  • 公共業務發生擴充套件的時候,方便集中管理

缺點:

  • 一個真實角色就會產生一個代理角色,程式碼量會翻倍,開發效率會變低

11.2 加深理解

程式碼實現:

  1. 介面

    public interface UserService {
        public void add();
        public void delete();
        public void update();
        public void query();
    }
    
  2. 真實角色

    // 真實物件
    public class UserServiceImpl implements UserService {
        public void add() {
            System.out.println("增加了一個使用者!");
        }
    
        public void delete() {
            System.out.println("刪除了一個使用者!");
        }
    
        public void update() {
            System.out.println("修改了一個使用者!");
        }
    
        public void query() {
            System.out.println("查詢了一個使用者!");
        }
    }
    
  3. 代理角色

    public class UserServiceProxy implements UserService {
    
        private UserServiceImpl userService;
    
        public void setUserService(UserServiceImpl userService) {
            this.userService = userService;
        }
    
        public void add() {
            log("add");
            userService.add();
        }
    
        public void delete() {
            log("delete");
            userService.delete();
        }
    
        public void update() {
            log("update");
            userService.update();
        }
    
        public void query() {
            log("query");
            userService.query();
        }
    
        // 日誌方法
        public void log(String msg){
            System.out.println("【Debug】使用了"+msg+"方法!");
        }
    }
    
  4. 客戶端訪問代理角色

    public class Client {
        public static void main(String[] args) {
            UserServiceImpl userService = new UserServiceImpl();
    
            UserServiceProxy proxy = new UserServiceProxy();
            proxy.setUserService(userService);
            proxy.add();
        }
    }
    

聊聊AOP

11.3 動態代理

  • 動態代理和靜態代理角色一樣
  • 動態代理的代理類是動態生成的,不是我們直接寫好的
  • 動態代理分為兩大類:基於介面的動態代理,基於類的動態代理
    • 基於介面:JDK動態代理【我們在這裡使用】
    • 基於類:cglib
    • Java位元組碼實現:Javasist

需要了解兩個類:Proxy:代理,InvocationHandler:呼叫處理程式

動態代理的好處:

  • 可以使真實角色的操作更加純粹,不用去關注一些公共的業務
  • 公共業務就交給了代理角色,實現了業務的分工
  • 公共業務發生擴充套件的時候,方便集中管理
  • 一個動態代理類代理的是一個介面,一般就是對應的一類業務
  • 一個動態代理類可以代理多個類,只要是實現了同一個介面即可

程式碼實現:

  • 動態生成代理類

    // 我們會用這個類自動生成代理類
    public class ProxylnvocationHandler implements InvocationHandler {
    
        // 被代理的介面
        private Object target;
    
        public void setTarget(Object target) {
            this.target = target;
        }
    
        // 生成得到代理類
        public Object getProxy(){
            return  Proxy.newProxyInstance(this.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
        }
    
        // 處理代理例項,並返回結果
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            log(method.getName());
            // 動態代理的本質,就是使用反射機制實現!
            Object result = method.invoke(target, args);
    
            return result;
        }
    
        public void log(String msg){
            System.out.println("執行了"+msg+"方法!");
        }
    }
    
  • 客戶端訪問代理角色

    public class Client {
        public static void main(String[] args) {
            // 真實角色
            UserServiceImpl userService = new UserServiceImpl();
            // 代理角色,不存在
            ProxylnvocationHandler pih = new ProxylnvocationHandler();
            // 設定要代理物件
            pih.setTarget(userService);
            // 動態生成代理類
            UserService proxy = (UserService) pih.getProxy();
            proxy.query();
        }
    }
    

12.AOP

12.1 什麼是AOP

AOP(Aspect Oriented Programming)意為:面向切面程式設計,通過預編譯方式和執行期動態代理實現程式功能的統一維護的一種技術。AOP是OOP的延續,是軟體開發中的一個熱點,也是Spring框架中的一個重要內容,是函數語言程式設計的一種衍生範型。利用AoP可以對業務邏輯的各個部分進行隔離,從而使得業務邏輯各部分之間的耦合度降低,提高程式的可重用性,同時提高了開發的效率。

12.2 AOP在Spring中的作用

提供宣告式事務,允許使用者自定義切面

  • 橫切關注點:跨越應用程式多個模組的方法或功能。即是與我們業務邏輯無關的,但是我們需要關注的部分,就是橫切關注點。如日誌,安全,快取,事務等等....
  • 切面(ASPECT):橫切關注點被模組化的特殊物件。即它是一個類。
  • 通知(Advice):切面必須要完成的工作。即它是類中的一個方法。
  • 目標(Target)︰被通知物件。
  • 代理(Proxy)︰向目標物件應用通知之後建立的物件。
  • 切入點(PointCut):切面通知執行的“地點“的定義。
  • 連線點(JointPoint):與切入點匹配的執行點。

SpringAOP中,通過Advice定義橫切邏輯,Spring中支援5種類型的Advice:

即AOP在不改變原有程式碼的情況下,去增加新的功能

12.3 使用Spring實現AOP

【重點】使用AOP之前,需要匯入一個依賴包

<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.7</version>
</dependency>

方式一:使用Spring的 API 介面 【主要是SpringAPI介面實現】

方式二:自定義類來實現AOP 【主要是切面定義】

方式三:使用註解實現

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

    <!--註冊bean-->
    <bean id="userService" class="com.mc.service.UserServiceImpl"/>
    <bean id="beforeLog" class="com.mc.log.BeforeLog"/>
    <bean id="afterLog" class="com.mc.log.AfterLog"/>

    <!--方式一: 使用原生的Spring API介面-->
    <!--配置aop: 需要匯入aop的約束-->
    <!--<aop:config>
        &lt;!&ndash;切入點: expression表示式,execution(要執行的位置)&ndash;&gt;
        <aop:pointcut id="pointcut" expression="execution(* com.mc.service.UserServiceImpl.*(..))"/>

        &lt;!&ndash;執行環繞增加&ndash;&gt;
        <aop:advisor advice-ref="beforeLog" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>

    </aop:config>-->

    <!--方式二: 自定義類-->
   <!-- <bean id="diy" class="com.mc.diy.DiyPointCut"/>
    <aop:config>
        &lt;!&ndash;自定義切面,ref 要引用的類&ndash;&gt;
        <aop:aspect ref="diy">
            &lt;!&ndash;切入點&ndash;&gt;
            <aop:pointcut id="point" expression="execution(* com.mc.service.UserServiceImpl.*(..))"/>
            &lt;!&ndash;通知&ndash;&gt;
            <aop:before method="before" pointcut-ref="point"/>
            <aop:after method="after" pointcut-ref="point"/>
        </aop:aspect>

    </aop:config>-->

    <!--方式三: 使用註解-->
    <bean id="annotationPointCut" class="com.mc.diy.AnnotationPointCut"/>
    <!--開啟註解支援   JDK(預設  proxy-target-class="false")  cglib(proxy-target-class="true")-->
    <aop:aspectj-autoproxy proxy-target-class="false"/>

</beans>

13.整合Mybatis

步驟:

  1. 匯入相關jar包
    • junit
    • mybatis
    • mysql資料庫
    • spring相關的
    • aop織入
    • mybatis-spring 【new】
<dependencies>
    <!--  junit驅動 -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>

    <!--  mysql驅動 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.21</version>
    </dependency>

    <!--  mybatis驅動 -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.2</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.3.5</version>
    </dependency>

    <!--Spring操作資料庫的話,還需要一個spring-jdbc包 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.3.5</version>
    </dependency>

    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.9.7</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.6</version>
    </dependency>
    
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.20</version>
        <scope>provided</scope>
    </dependency>

</dependencies>
  1. 編寫配置檔案

  2. 測試

13.1 回憶Mybatis

  1. 編寫實體類
  2. 編寫核心配置檔案
  3. 編寫介面
  4. 編寫Mapper.xml
  5. 測試

13.2 Mybatis-Spring

  1. 編寫資料來源配置

    <!--DataSource: 使用Spring的資料來源替換Mybatis的配置
            我們這裡使用Spring提供的JDBC: org.springframework.jdbc.datasource
        -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;serverTimezone=GMT%2B8&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;allowPublicKeyRetrieval=true"/>
        <property name="username" value="root"/>
        <property name="password" value="mc123456"/>
    </bean>
    
  2. sqlSessionFactory

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--繫結Mybatis配置檔案-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath:com/mc/mapper/*.xml"/>
    </bean>
    
  3. sqlSessionTemplate

    <!--SqlSessionTemplate: 就是我們使用的sqlSession-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <!--只能使用構造器注入sqlSessionFactory,因為它沒有set方法-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>
    
  4. 需要給介面加實現類

    public class UserMapperImpl implements UserMapper {
    
        // 我們所有的操作,在原來都使用sqlSession來執行,現在都使用SqlSessionTemplate
        private SqlSessionTemplate sqlSession;
    
        public void setSqlSession(SqlSessionTemplate sqlSession) {
            this.sqlSession = sqlSession;
        }
    
        public List<User> selectUser() {
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            return mapper.selectUser();
        }
    }
    
  5. 將自己寫的實現類,注入到Spring中

    <bean id="userMapper" class="com.mc.mapper.UserMapperImpl">
        <property name="sqlSession" ref="sqlSession"/>
    </bean>
    
  6. 測試使用即可!

14.宣告式事務

14.1 事務

  • 把一組業務當成一個業務來做,要麼都成功,要麼都失敗!
  • 事務在專案開發中,十分的重要,涉及到資料的一致性問題,不能馬虎!
  • 確保完整性和一致性

事務ACID原則:

  • 原子性
  • 一致性
  • 隔離性
    • 多個業務可能操作同一個資源,防止資料損壞
  • 永續性
    • 事務一旦提交,無論系統發生什麼問題,結果都不會再被影響,被持久化的寫到儲存器中

14.2 Spring中的事務管理

  • 宣告式事務:AOP

    <!--配置宣告式事務-->
    <bean id="transactionManage" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--結合AOP實現事務的織入-->
    <!--配置事務通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManage">
        <!--給哪些方法配置事務-->
        <!--配置事務的傳播特性: propagation-->
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED"/>
            <tx:method name="add" propagation="REQUIRED"/>
            <tx:method name="delete" propagation="REQUIRED"/>
            <tx:method name="update" propagation="REQUIRED"/>
            <tx:method name="query" read-only="true"/>
        </tx:attributes>
    </tx:advice>
    
    <!--配置事務切入-->
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.mc.mapper.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>
    
    
  • 程式設計式事務:需要在程式碼中進行事務的管理

思考:為什麼需要事務?

  • 如果不配置事務,可能存在資料提交不一致的情況
  • 如果我們不在Spring中去配置宣告式事務,我們就需要在程式碼中手動配置事務
  • 事務在專案的開發中十分重要,涉及到資料的一致性和完整性問題,不容馬虎!