Spring筆記(狂神說Java)


1、Spring

1.1、簡介

  • Spring:春---->給軟件行業帶來了春天

  • 2002,首次推出了Spring框架的雛形: interface21框架

  • Spring框架即以interface21框架為基礎,經過重新設計,並不斷豐富其內涵,於2004年3月24日發布了1.0正式

  • Rod Johnson,Spring Framework創始人,著名作者。很難想象Rod Johnson的學歷,真的讓好多人大吃一
    驚,他是悉尼大學的博士,然而他的專業不是計算機,而是音樂學

  • spring理念:使現有的技術更加容易使用,本身是一個大雜燴,整合了現有的技術框架

  • SSH : Struct2 + Spring + Hibernate

  • SSM:SpringMvc + Spring + Mybatis

官網: https://spring.io/projects/spring-framework#overview
官方下載地址: http://repo.spring.io/release/org/springframework/spring
GitHub: https://github.com/spring:projects/spring-framework

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.3.9</version>
</dependency>

1.2、優點

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

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

1.3、組成

1.4、拓展

在Spring的官網有這個介紹:現代化的Java開發!說白就是基於Spring的開發!

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

因為現在大多數公司都在使用SpringBoot進行快速開發,學習SpringBoot的前提 ,需要完全掌握Spring及
SpringMVC!承上啟下的作用!

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

2、IOC理論推導

  1. UserDao接口
  2. UserDaolmpl實現類
  3. UserService業務接口
  4. UserServicelmpl業務實現類

在我們之前的業務中,用戶的需求可能會影響我們原來的代碼,我們需要根據用戶的需求去修改原代碼!

如果代碼量非常大,修改一次的成本代價十分昂貴

使用set接口實現

private UserDao userDao;

//利用set進行動態實現值得注入
public void setUserDao(UserDao userDao){
    this.userDao = userDao;
}
  • 之前,程序是主動創建對象!控制權在程序猿手上!
  • 使用了set注入后,程序不再具有主動性,而是變成了被動的接受對象,系統耦合性大大降低,可以更加的專注在業務的實現上,這是IOC的原型

IOC本質

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

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

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

3、HelloSpring

User.java

public class User {
    private int id;
    private String username;
    private String password;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
            "id=" + id +
            ", username='" + username + '\'' +
            ", password='" + password + '\'' +
            '}';
    }
}

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 = 變量名(標識)-->
    <!--class = new的對象(一個類所在的位置,全類名)-->
    <!--property 相當於給對象中的屬性設值,其中必須要有set方法,否則無法注入-->
    <!--value:給對象屬性取值   ref:指向具體的對象(bean的id值)-->
    <bean id="user" class="com.hbxy.pojo.User">
        <property name="id" value="1"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>
</beans>

Test.java

public class Test {
    public static void main(String[] args) {
        //獲取上下文對象
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        //獲取bean
        User user = (User) context.getBean("user");
        //輸出結果
        System.out.println(user.toString());
    }
}

思考問題?

  • Hello 對象是誰創建的?
    hello對象是由Spring創建的

  • Hello 對象的屬性是怎么設置的?
    hello對象的屬性是由Spring容器設置的,

這個過程就叫控制反轉:

控制:誰來控制對象的創建,傳統應用程序的對象是由程序本身控制創建的,使用Spring后 ,對象是由Spring來創
建的.

反轉:程序本身不創建對象,而變成被動的接收對象.
I
依賴注入:就是利用set方法來進行注入的.

IOC是- -種編程思想,由主動的編程變成被動的接收.

可以通過newClassPathXmlApplicationContext去瀏覽一下底層源碼 .

到了現在,我們徹底不用再程序中去改動了,要實現不同的操作,只需要在xml配置文件中進行修改,所謂的
IoC,-一句話搞定:對象由Spring來創建,管理,裝配!

4、IOC創建對象的方式

  1. 使用無參構造創建對象,默認。
  2. 使用有參構造

User.java

public class User {
    private String username;
    private String password;

    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

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

下標賦值

<?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="user" class="com.hbxy.pojo.User">
        <constructor-arg index="0" value="root"/>
        <constructor-arg index="1" value="123456"/>
    </bean>
</beans>

類型賦值(不建議使用),引用類型必須全稱,默認從上到下

<bean id="user" class="com.hbxy.pojo.User">
    <!--引用類型必須全稱-->
    <constructor-arg type="java.lang.String" value="root"/>
    <constructor-arg type="java.lang.String" value="123456"/> <!--分不清是哪個參數,不建議使用-->
</bean>

直接通過參數名

<?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="user" class="com.hbxy.pojo.User">
        <constructor-arg name="username" value="root"/>
        <constructor-arg name="password" value="123456"/>
    </bean>
</beans>

Spring類似於婚介網站!

你想不想要,對象都在里面。注冊bean之后用不用被實例化。

總結:在配置文件加載的時候,容器(applicationContext)中管理的對象就已經初始化(實例化)

5、Spring配置

5.1、別名

<bean id="user" class="com.hbxy.pojo.User">
    <constructor-arg type="java.lang.String" value="root"/>
    <constructor-arg type="java.lang.String" value="123456"/>
</bean>
<!--如果添加了別名,也可以通過別名獲取到這個對象-->
<alias name="user" alias="userNew"/>

5.2、Bean的配置

  • id:bean的id標識符
  • class:bean對象所對應的類型(包名+類名)
  • name:別名,更高級,可以同時取多個別名。
<bean id="userT" class="com.hbxy.pojo.UserT" name="userT1 userT2,userT3">
    <property name="username" value="root"/>
</bean>

5.3、import

這個import,一般用於團隊開發,可以將多個配置文件,導入合並一個

假設,項目中有多個人開發,這三個人負責不同的人開發,不同的類需要注冊在不同的bean中,我們可以利用import,將所有人的beans.xml合並為總的

  • 張三
  • 李四
  • 王五
  • applicationContext.xml

使用的時候使用總的就可以了

<import resource="beans.xml"/>
<import resource="beans2.xml"/>
<import resource="beans3.xml"/>

6、DI依賴注入

6.1、構造器注入

前面講過

6.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> hobbies;
        private Map<String,String> card;
        private Set<String> games;
        private Properties info;
        private String wife;
    }
    
  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 http://www.springframework.org/schema/beans/spring-beans.xsd">
    
        <bean id="student" class="com.hbxy.pojo.Student">
            <!--1.普通值注入-->
            <property name="name" value="小明"/>
            <property name="address" ref="address"/>
        </bean>
    </beans>
    
  4. 測試類

    public class Test {
        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 http://www.springframework.org/schema/beans/spring-beans.xsd">
    
        <bean id="address" class="com.hbxy.pojo.Address">
            <property name="address" value="圍場"/>
        </bean>
        <bean id="student" class="com.hbxy.pojo.Student">
            <!--1.普通值注入-->
            <property name="name" value="小明"/>
            <!--2.Bean注入,ref-->
            <property name="address" ref="address"/>
            <!--3.數組注入-->
            <property name="books">
                <array>
                    <value>紅樓夢</value>
                    <value>三國演義</value>
                    <value>西游記</value>
                    <value>水滸傳</value>
                </array>
            </property>
            <!--4.list注入-->
            <property name="hobbies">
                <list>
                    <value>學習</value>
                    <value>看書</value>
                    <value>敲代碼</value>
                </list>
            </property>
            <!--5.map-->
            <property name="card">
                <map>
                    <entry key="身份證" value="130828199221213456"/>
                    <entry key="電話" value="19822384587"/>
                    <entry key="銀行卡" value="6564512316512"/>
                </map>
            </property>
            <!--6.Set-->
            <property name="games">
                <set>
                    <value>LOL</value>
                    <value>COC</value>
                    <value>BOB</value>
                </set>
            </property>
            <!--7.NULL-->
            <property name="wife">
                <null/>
            </property>
            <!--8.Properties-->
            <property name="info">
                <props>
                    <prop key="學號">18851004</prop>
                    <prop key="性別">男</prop>
                    <prop key="愛好">睡覺</prop>
                </props>
            </property>
        </bean>
    
    </beans>
    

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

    <!--p命名空間注入,可以直接注入屬性的值:property-->
    <bean id="userp" class="com.hbxy.pojo.User" p:username="root" p:password="123456"/>
    <!--c命名空間注入,通過構造器注入-->
    <bean id="userc" class="com.hbxy.pojo.User" c:_0="xiaoming" c:_1="188324"/>
</beans>

測試:

import com.hbxy.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class UserTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("user.xml");
        User user = (User) context.getBean("user");
        System.out.println(user);
    }
    @Test
    public void userTest(){
        ApplicationContext context = new ClassPathXmlApplicationContext("user.xml");
        User user = context.getBean("userc", User.class);
        System.out.println(user);
    }
}

注意點:

c命名空間和p命名空間不能直接使用,需要導入xml約束!

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

6.4、bean的作用域

  1. 單例模式(Spring默認機制)(每次從容器中get的時候,都是一個對象)

    <bean id="userc" class="com.hbxy.pojo.User" c:_0="xiaoming" c:_1="188324" scope="singleton"/>
    
  2. 原型模式(每次從容器中get的時候,都會產生新對象)

    <bean id="userc" class="com.hbxy.pojo.User" c:_0="xiaoming" c:_1="188324" scope="prototype"/>
    

    3.其余的request、session、application、這些只能在web開發中使用!

7、Bean的自動裝配

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

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

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

7.1、測試

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

7.2、ByName自動裝配

<bean id="cat" class="com.hbxy.pojo.Cat"/>
<bean id="dog" class="com.hbxy.pojo.Dog"/>
<!--
	byName:會自動在容器上下文中查找,和自己對象set方法后面的值對應的 bean id7.3-->
<bean id="person" class="com.hbxy.pojo.Person" autowire="byName">
<property name="name" value="小明"/>
</bean>

7.3、ByType自動裝配

<bean class="com.hbxy.pojo.Cat"/>
<bean class="com.hbxy.pojo.Dog"/>
<!--
	byName:會自動在容器上下文中查找,和自己對象屬性類型相同的bean-->
<bean id="person" class="com.hbxy.pojo.Person" autowire="byType">
<property name="name" value="小明"/>
</bean>

小結:

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

7.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>
    

@Autowire

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

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

public class People {
    @Autowired(required=false)
    private Cat cat;
    @Autowired
    private Dog dog;
    private String name;
}
@Nullable 字段標志的注解,說明這個字段可以為null

如果@Autowired自動裝配環境比較復雜,也就是不同一個類中不同的id的bean很多。自動裝配無法通過一個注解完成的時候

我們可以使用@Qualifier(value = "dog")去配合使用,指定一個唯一的id對象

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

@Resource(name="dog")也可以,並且@Resource(name="dog") =@Autowired+@Qualifier(value = "dog")

區別:

  • @autowire通過byType和byName實現,而且必須要求這個對象存在,不存在配合@Qualifier(value = "dog") 使用
  • @resource默認通過byName和byType實現,如果找不到,通過@Resource(name="dog")實現

8、使用注解開發

在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

@Component//相當於<bean id="user" class="com.hbxy.pojo.User"/>
public class User {
    public String name = "小明";
}

2.屬性如何注入

@Component
public class User {
    @Value("小明")
    public String name;<property name="name" value="小明">
}

也可以放在set方法上

@Component
public class User {

    public String name;
    @Value("小明")
    public void setName(String name) {
        this.name = name;
    }
}

3.衍生的注解

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

  • dao 【@Repository】

  • service 【@Service】

  • controller 【@Controller】

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

4.自動裝配

見上邊

5.作用域

@Component
@Scope("singleton")
public class User {

    public String name;
    @Value("小明")
    public void setName(String name) {
        this.name = name;
    }
}

6.小結

xml與注解

  • xml更加萬能,維護簡單
  • 注解,不是自己的類,使用不了,維護復雜

最佳實踐:

  • xml用來管理bean
  • 注解只用來完成屬性的注入
  • 需要開啟注解支持
<!--指定要掃描的包,這個包下的注解就會生效-->
<context:component-scan base-package="com.hbxy"/>
<!--開啟注解支持-->
<context:annotation-config/

9、完全使用Java的方式配置Spring

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

JavaConfig是Spring的一一個子項目,在Spring 4之后,它成為了一-個核心功能!

@Configuration //這個也會Spring容器托管,注冊到容器中,因為他本來就是一個@Component,@Configuration代表這是一個配置類, 就和我們之前看的beans.xml

@ComponentScan("com.hbxy.pojo")
@Import(Config2.class)
public class MyConfig {

    @Bean
    public User getUser(){
        return new User();
    }

}
@Component
public class User {

    @Value("dong")
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

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

這種純java配置方式

在springboot中,隨處可見

10、代理模式

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

代理模式的分類:

  • 靜態代理、
  • 動態代理

10.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(Host host) {
        this.host = host;
    }

    public void rent() {
        seeHouse();
        host.rent();
        fare();
    }

    public void seeHouse(){

        System.out.println("看房子");
    }
    public void fare(){

        System.out.println("收錢");
    }
}

4.客戶端訪問代理角色

public class Clint {
    public static void main(String[] args) {
        Host host = new Host();
        Proxy proxy = new Proxy(host);
        proxy.rent();
    }
}

代理模式的好處: .

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

缺點:

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

10.2、加深理解

代碼:08-demo02

10.3、動態代理

  • 動態代理和靜態代理一樣
  • 動態代理類是動態生成的,不是我們直接寫好的!
  • 基於接口的動態代理和基於類的動態代理
    • 基於接口:JDK動態代理 【使用】
    • 基於類:cglib
    • 基於字節碼實現:javasist

需要了解兩個類:Proxy:代理、InvocationHandler:調用處理程序

InvocationHandler

Proxy

動態代理的好處: .

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

通用:

/**
 * 會用這個類自動生成代理類
 */
public class ProxyInvocationHandler 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 {

        //動態代理的本質,就是使用反射機制實現
        Object result = method.invoke(target, args);

        return result;
    }
}

Test.java

public class Clint {
    public static void main(String[] args) {
        UserServiceImpl userService = new UserServiceImpl();
        ProxyInvocationHandler pih = new ProxyInvocationHandler();
        pih.setTarget(userService);
        UserService proxy = (UserService) pih.getProxy();
        proxy.add();
    }
}

11、AOP

11.1、什么是AOP

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

11.2、AOP在Spring中的應用

提供聲明式事務:允許用戶自定義切面


11.3、使用Spring實現Aop

重點:使用AOP織入,需要導入一個依賴包

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

方式一:使用Spring的API 接口【主要是接口實現】

<?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.hbxy.service.UserServiceImpl"/>
    <bean id="log" class="com.hbxy.log.Log"/>
    <bean id="afterLog" class="com.hbxy.log.AfterLog"/>

    <!--方式一:使用原生API 接口-->
    <!--配置AOP:需要導入aop約束-->
    <aop:config>
        <!--切入點 :expression:表達式  execution(要執行的位置)-->
        <aop:pointcut id="pointcut" expression="execution(* com.hbxy.service.UserServiceImpl.*(..))"/>
        <!--執行環繞增強-->
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
    </aop:config>
</beans>

Log.java

public class Log implements MethodBeforeAdvice {

    //method: 要執行的目標對象的方法
    //objects:參數
    //target:目標對象
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println(target.getClass().getName()+"的"+method.getName()+"被執行了");
    }
}

AfterLog.java

public class AfterLog implements AfterReturningAdvice {
    /**
     *
     * @param returnValue:返回值
     * @param method:被激活的方法
     * @param args:方法的參數
     * @param target
     * @throws Throwable
     */
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println("執行了"+method.getName()+"返回結果為"+returnValue);
    }
}

Test.java

public class MyTest {
    public static void main(String[] args) {

        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //動態代理代理的是接口
        UserService userService = (UserService) context.getBean("userService");
        userService.add();
    }
}

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

<!--方式二:自定義類-->
    <bean id="diy" class="com.hbxy.diy.DiyPointCut"/>
    <aop:config>
        <!--自定義切面-->
        <aop:aspect ref="diy">
            <!--切入點-->
            <aop:pointcut id="point" expression="execution(* com.hbxy.service.UserServiceImpl.*(..))"/>
            <!--通知-->
            <aop:before method="before" pointcut-ref="point"/>
            <aop:after method="after" pointcut-ref="point"/>
        </aop:aspect>
    </aop:config>

方式三:使用注解實現

<bean id="annotationPointCut" class="com.hbxy.diy.AnnotationPointCut"/>
<!--開啟注解支持-->
<aop:aspectj-autoproxy/>
@Aspect //標注此類是切面類
public class AnnotationPointCut {

    @Before("execution(* com.hbxy.service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("方法執行前");
    }

    @After("execution(* com.hbxy.service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("方法執行后");
    }

    @Around("execution(* com.hbxy.service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint point) throws Throwable {

        System.out.println("執行前");
        Signature signature = point.getSignature();//獲得簽名
        System.out.println("signature"+signature);
        Object proceed = point.proceed();
        System.out.println("執行后");
    }
}

12、整合Mybatis

步驟:

  1. 導入依賴
    • Junit
    • mybatis
    • mysql數據庫
    • aop織入
    • mybatis-spring【new】
  2. 編寫配置文件
  3. 測試

12.1、回憶Mybatis

  1. 編寫實體類
  2. 編寫Mapper接口
  3. 編寫Mapper.xml
  4. 編寫配置文件
  5. 測試

12.2、Mybatis-spring

  1. 編寫數據源配置
  2. sqlSessionFactory
  3. sqlSessionTemplete
  4. 需要給接口加實現類
  5. 將自己寫的實現類注入到spring中
  6. 測試使用

整合

方法一:

UserMapperImpl

package com.mapper;

import com.pojo.User;
import org.mybatis.spring.SqlSessionTemplate;

import java.util.List;

public class UserMapperImpl implements UserMapper {

    private SqlSessionTemplate sqlSessionTemplate;

    public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
        this.sqlSessionTemplate = sqlSessionTemplate;
    }

    public List<User> selectUser() {
        UserMapper mapper = sqlSessionTemplate.getMapper(UserMapper.class);
        return mapper.selectUser();
    }
}

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>

    <typeAliases>
        <package name="com.pojo"/>
    </typeAliases>

</configuration>

spring-dao.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"
       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">

    <!--data source-->
    <bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://111.230.212.103:3306/mybatis?userSSL=true&amp;
                userUnicode=true&amp;characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="hdk123"/>
    </bean>

    <!--sqlsession-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="datasource" />
        <!--bound mybatis-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath:com/mapper/UserMapper.xml"/>
    </bean>

    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>

    <bean id="userMapper" class="com.mapper.UserMapperImpl">
        <property name="sqlSessionTemplate" ref="sqlSession"></property>
    </bean>

</beans>

test

import com.mapper.UserMapper;
import com.pojo.User;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.IOException;


public class Mytest {


    public static void main(String[] args) throws IOException {

        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
        UserMapper userMapper = context.getBean("userMapper", UserMapper.class);

        for (User user : userMapper.selectUser()) {
            System.out.println(user);
        }
    }
}

方法二:

<?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">

    <!--data source-->
    <bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://111.230.212.103:3306/mybatis?userSSL=true&amp;
                userUnicode=true&amp;characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="hdk123"/>
    </bean>

    <!--sqlsession-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="datasource" />
        <!--bound mybatis-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath:com/mapper/UserMapper.xml"/>
    </bean>

    <!--<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">-->
        <!--<constructor-arg index="0" ref="sqlSessionFactory"/>-->
    <!--</bean>-->

    <!--<bean id="userMapper" class="com.mapper.UserMapperImpl">-->
        <!--<property name="sqlSessionTemplate" ref="sqlSession"></property>-->
    <!--</bean>-->

    <bean id="userMapper2" class="com.mapper.UserMapperIml2">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
    </bean>

</beans>
package com.mapper;

import com.pojo.User;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.support.SqlSessionDaoSupport;

import java.util.List;

public class UserMapperIml2 extends SqlSessionDaoSupport implements UserMapper {
    public List<User> selectUser() {
        SqlSession sqlSession = getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.selectUser();
    }
}

13、聲明式事務

1、回顧事務

  • 把一組業務當成一個業務來做,要么成功,要么失敗
  • 事務在項目開發,十分的重要,涉及到數據的一致性問題
  • 確保完整性和一致性

事務的ACID原則:

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

2、Spring中的事務管理

  • 聲明式事務:AOP
  • 編程式事務:需要在代碼中,進行事務管理

思考:
為什么需要事務?

  • 如果不配置事務,可能存在數據提交不一致的情況下;
  • 如果我們不在SPRING中去配置聲明式事務,我們就需要在代碼中手動配置事務!
  • 事務在項目的開發中十分重要,設計到數據的一致性和完整性問題,不容馬虎!

applicationContext.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">

    <import resource="spring-mapper.xml"/>
    <bean id="userMapper" class="com.hbxy.mapper.Impl.UserMapperImpl"/>

</beans>

spring-mapper.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"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/context
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
        https://www.springframework.org/schema/tx/spring-tx.xsd">
    <!--開啟注解支持-->
    <context:annotation-config/>
    <context:component-scan base-package="com.hbxy.*"/>

    <!--加載外部配置文件-->
    <context:property-placeholder location="classpath:db.properties" />

    <!--DateSource:使用Spring的數據源替換Mybatis配置  c3p0 dbcp druid
   這里使用Spring提供的JDBC-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <!--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/hbxy/mapper/*.xml"/>
    </bean>

    <!--SqlSessionTemplate:就是我們使用的sqlSession-->
    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        <!--只能使用構造器注入sqlSessionFactory,因為沒有set方法-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>

    <!--配置聲明式事務-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--<constructor-arg ref="dataSource" />-->
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--結合AOP實現事務的織入-->
    <!--配置事務的通知-->
    <tx:advice id="txActive" transaction-manager="transactionManager">
        <!--給哪些方法配置事務-->
        <!--配置事務的傳播特性:new propagation=-->
        <tx:attributes>
            <tx:method name="add" propagation="REQUIRED"/>
            <tx:method name="delete" propagation="REQUIRED"/>
            <tx:method name="update" propagation="REQUIRED"/>
            <tx:method name="select" propagation="REQUIRED"/>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

    <!--配置事務切入-->
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.hbxy.mapper.*.*(..))"/>
        <aop:advisor advice-ref="txActive" pointcut-ref="txPointCut"/>
    </aop:config>
</beans>

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <setting name="logImpl" value="LOG4J"/>
    </settings>
    <typeAliases>
        <package name="com.hbxy.pojo"/>
    </typeAliases>
</configuration>

db.properties

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT
jdbc.username=root
jdbc.password=123456


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM