Spring学习笔记

Spring笔记

1、Spring

1.1、简介

  • Spring:春天---->给软件环境带来了春天

  • 2002年,首次推出了Spring框架的雏形;interface21

  • 2004年3月24日,

  • Rod Johnson

  • Spring理念: 使现有的技术更加容易使用,本身是一个大杂烩,整合了现有的技术框架

  • SSH:Struct2 + Spring + Hibernate

  • SSM:SpringMvc + Spring + mybatis

官网:https://repo1.maven.org/maven2/org/springframework/spring/

官方下载地址:https://repo1.maven.org/maven2/org/springframework/spring/

github:https://github.com/spring-projects/spring-framework

maven:

在这里插入图片描述

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


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

1.2、优点

  • Spring是一个开源的免费的框架(容器)
  • Spring是一个轻量级的,非入侵式的框架
  • 控制反转(IOC),面向切面编程(AOP)
  • 支持事务处理,对框架整合的支持

总结:Spring就是一个轻量级的控制反转(IOC)和面向切面编程(AOP)的框架

1.3、组成

在这里插入图片描述

1.4、扩展

现在带花的java开发,就是基于Spring的开发

在这里插入图片描述

  • Spring Boot
    • 一个快速开发的脚手架
    • 基于SpringBoot可以快速的开发单个微服务
    • 约定大于配置
  • Spring Cloud
    • SpringCloud是基于SpringBoot实现的

因为现在大多数公司都在使用SpringBoot进行快速开发,学习SpringBoot的前提,需要完全掌握Spring及SpringMVC 承上启下的作用

弊端:发展了太久之后,违背了原来的理念!配置十分繁琐,人称配置地狱

2、IOC理论推导

  1. UserDao接口
  2. UserDaoImpl实现类
  3. UserService 业务接口
  4. UserService Impl业务实现类

在我们之前的业务中,用户的需求可能回应i昂我们原来的代码,我们需要根据用户的需求去修改代码,如果程序代码量十分大,修改一次的成本十分昂贵

在这里插入图片描述

我们们用set接口实现,已经发生了革命性的变化

public class UserServiceImpl implements UserService{
    private UserDao userDao;

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
  • 之前是程序主动创建对象!控制权在程序员手上!
  • 使用了set诸如狗,程序不再具有主动性

这种思想,从本质上解决了问题,我们程序员不用再去管理对象的创建了,系统的耦合性大大降低,可以更加专注的在业务的实现上。这是IOC的原型!

在这里插入图片描述

IOC本质

控制反转IOC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现IOC的一种方法,也有人认为DI只是IOC的另一种说法。没有IOC的程序中,我们使用面向对象编程,对象的创建与对象间的依赖关系完全硬编码在程序中,对象的创建方式由程序自己控制,控制反转后将对象的创建转移给第三方,所谓控制反转就是:获得依赖对象的方式反转了。

总结:spring是IOC容器通过依赖注入的方式实现控制反转

控制反转是一种通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式。在Spring中实现控制反转的是 IOC 容器,其实现方法是依赖注

3、HelloSpring

public class MyTest {
    public static void main(String[] args) {
        //获取Spring的上下文对象
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        //我们现在的对象都在Spring中管理了,我们要使用,直接去里面取出来就可以。
        Hello hello = (Hello) context.getBean("hello");
        System.out.println(hello.toString());
    }
}

思考问题:

  • Hello对象是谁创建的?
  • hello对象是由Spring创建的
  • hello对象的属性是怎么设置的?
  • hello对象的属性是由Spring容器配置的

这个过程就叫控制反转:

控制:谁来控制对象的创建,传统应用程序的对象是由程序本身创建的,使用Spring后,对象由Spring创建。

反转:程序本身不创建对象,而变成被动的接收对象

依赖注入:就是利用set方法来进行注入

IOC是一种编程思想,由主动的编程编程被动的接收;

可以通过newClassPathXmlApplicationContext去浏览底层源码。

到了现在,我们彻底不用在程序中去改动了,要实现不同的操作,只需要在xml配置文件中和进行修改,所谓的IOC:就是对象由Spring创建,管理,装配!

4、IOC创建对象的方式

  1. 使用无参构造创造方法创建对象,默认!

  2. 加入我们要使用有参构造实现创建对象

    1. 下标赋值
    <!--下标赋值-->
        <bean id="user" class="com.zhao.pojo.User">
            <constructor-arg index="0" value="昭昭1"/>
        </bean>
    
    1. 第二种:通过类型创建
    <!--第二种: 通过类型创建:   不建议使用,如果两个参数类型相同-->
        <bean id="user" class="com.zhao.pojo.User">
            <constructor-arg type="java.lang.String" value="昭昭2"/>
        </bean>
    
    1. 第三种:直接通过参数名
    <!--    第三种:直接通过参数名-->
        <bean id="user" class="com.zhao.pojo.User">
            <constructor-arg name="name" value="昭昭3"/>
        </bean>
    

总结:在配置文件加载的时候,容器中管理的对象就已经被初始化了!

5、Spring配置

5.1、别名

<!--别名-->
    <alias name="user" alias="user2"/>

5.2、Bean的配置

<!--
id:bean的唯一标识符,相当于我们的对象名
class:bean对象所对应的全限定名:包名+类型
name;也是别名,而且name可以取多个别名
-->
    <bean id="user" class="com.zhao.pojo.User" name="user3,user5">
        <constructor-arg name="name" value="昭昭3"/>
    </bean>

5.3、import

一般用于团队开发使用,它可以将多个配置文件,导入合并为一个

假设,现在项目中有多个人开发,这三个人复制不同的开发,不同的类需要注册在不同的bean中,我们可以利用Import将所有人的beans.xml合并为一个总的xml

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

使用的时候,直接用总的配置就可以了

6、依赖注入

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;
    }

    @Override
    public String toString() {
        return "Address{" + "address='" + address + '\'' + '}';
    }
}
  1. 真实测试对象
package com.zhao.pojo;

import java.util.*;

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;

    public String getName() {
        return name;
    }

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

    public Address getAddress() {
        return address;
    }

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

    public String[] getBooks() {
        return books;
    }

    public void setBooks(String[] books) {
        this.books = books;
    }

    public List<String> getHobbies() {
        return hobbies;
    }

    public void setHobbies(List<String> hobbies) {
        this.hobbies = hobbies;
    }

    public Map<String, String> getCard() {
        return card;
    }

    public void setCard(Map<String, String> card) {
        this.card = card;
    }

    public Set<String> getGames() {
        return games;
    }

    public void setGames(Set<String> games) {
        this.games = games;
    }

    public Properties getInfo() {
        return info;
    }

    public void setInfo(Properties info) {
        this.info = info;
    }

    public String getWife() {
        return wife;
    }

    public void setWife(String wife) {
        this.wife = wife;
    }

    @Override
    public String toString() {
        return "Student{" + "name='" + name + '\'' + ", address=" + address + ", books=" + Arrays.toString(books) + ", hobbies=" + hobbies + ", card=" + card + ", games=" + games + ", info=" + info + ", wife='" + wife + '\'' + '}';
    }
}

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

    <bean id="student" class="com.zhao.pojo.Student">
<!--        第一种,普通值注入,value-->
        <property name="name" value="昭昭"/>
    </bean>
</beans> 
  1. 测试类
public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Student student = (Student) context.getBean("student");
        System.out.println(student.toString());
    }
}

完善注入信息

<?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.zhao.pojo.Address"/>

    <bean id="student" class="com.zhao.pojo.Student">
<!--        第一种,普通值注入,value-->
        <property name="name" value="坤坤"/>
<!--        第二种:bean注入 ref-->
        <property name="address" ref="address"/>
<!--        第三种:数组注入-->
        <property name="books">
            <array>
                <value>只因</value>
                <value></value>
                <value>太美</value>
                <value>baby</value>
            </array>
        </property>
<!--        第四种:List注入-->
        <property name="hobbies">
            <list>
                <value></value>
                <value></value>
                <value>Rap</value>
                <value>篮球</value>
            </list>
        </property>
<!--        第五种:map注入-->
        <property name="card">
            <map>
                <entry key="身份整" value="ikun123"/>
                <entry key="真爱粉证明" value="哥哥最帅"/>
                <entry key="银行卡" value="gg1234455"/>
            </map>
        </property>
<!--        第六种:set-->
        <property name="games">
            <set>
                <value>爱坤快打</value>
                <value>鸡大师</value>
                <value>篮球之神</value>
            </set>
        </property>
<!--        null-->
        <property name="wife">
            <null/>
        </property>
<!--        -->
        <property name="info">
            <props>
                <prop key="爱坤证号">123123123</prop>
                <prop key="学号">2012210236</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="user" class="com.zhao.pojo.User" p:name="zz" p:age="12">


    </bean>

    <!--    c命名空间注入,通过有参的构造器注入:constructs-args-->
    <bean id="user2" class="com.zhao.pojo.User" c:name="kunkun" c:age="15"/>
</beans>

测试

  @Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("userBeans.xml");
        User user = (User) context.getBean("user2");
        System.out.println(user.toString());
    }

注意点:p命名和c命名空间不能直接使用,需要导入xml约束

p命名:xmlns:p=“http://www.springframework.org/schema/p”

c命名:xmlns:c=“http://www.springframework.org/schema/c”

6.4、bean的作用域

在这里插入图片描述

1、代理模式,(Spring默认机制)

在这里插入图片描述

<bean id="user2" class="com.zhao.pojo.User" c:name="kunkun" c:age="15" scope="singleton"/>

2、原型模式:每次从容器中get的时候,都会产生新的对象

在这里插入图片描述

<bean id="accountService" class="com.something.DefaultAccountService" scope="prototype"/>

3、其余的request,session。application,这些只能在web开发中使用到

7、自动装配

  • 自动装配是Spring满足bean依赖的一种方式
  • Spring会在上下文中自动寻找,并自动给bean自动装配属性

在spring中有三种配置方式

  1. 在xml中显示的配置
  2. 在java中显示的配置
  3. 隐式的自动装配bean【重要】

7.1、测试

1.环境搭建

  • 一个人有两个宠物

7.2、ByName自动装配

    <bean id="cat" class="com.zhao.pojo.Cat"/>
    <bean id="dog" class="com.zhao.pojo.Dog"/>
<!-- byName:会自动在容器的上下文中查找,和自己对象set方法对应的id beanid!   -->
    <bean id="people" class="com.zhao.pojo.People" autowire="byName">
        <property name="name" value="zz"/>
    </bean>

7.3、ByType自动装配

    <bean class="com.zhao.pojo.Cat"/>
    <bean class="com.zhao.pojo.Dog"/>
<!-- byName:会自动在容器的上下文中查找,和自己对象set方法对应的id beanid!(但是id要唯一且对应)
     byType:会自动在容器的上下文中查找,和自己对象属性类型相同的bean(但是一个类里只能由一个对象)!
     byType可以省略bean中的id 因为是通过类(所在的包)查找的

   -->
    <bean id="people" class="com.zhao.pojo.People" autowire="byType">
        <property name="name" value="zz"/>
    </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. 导入约束
  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

直接在属性上使用即可!也可与i在set方式上使用

使用autowired我们就可以不用编写set方法了,前提是你这个自动装配的属性在IOC(Spring)容器中存在且符合名字byName (首先byType,如果一个类中有多个属性,就是用byName)

科普:

@nullable 字段标记了这个注解,说明这个字段可以为空


public @interface Autowired {
    boolean required() default true;
}

测试代码

package com.zhao.pojo;

import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;

@Data
public class People {
    //如果显示的定义了Autowired的required属性为false,说明这个对象可以为null,否则不允许为空
    @Autowired(required = false)
    private Cat cat;
    @Autowired
    private Dog dog;
    private String name;
}

如果自动装配的环境比较复杂,自动装配无法通过一个注解【@autowired】完成的时候,我们可以使用@Qualifier(value=“xxx”)去配合autowired的使用,指定唯一的bean对象注入。

如果xml文件中同一个对象被多个bean使用,Autowired无法按类型找到,可以用@Qualifier指定id查找

    @Autowired
    @Qualifier(value = "cat")
    private Cat cat;

@Resouse

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

小结:

@Resouse和@autowired的区别:

  • 都是用来自动装配的,都可以放在属性字段上
  • @Autowired是默认通过byType的方式,当匹配到多个同类型时,使用ByName进行装配
  • @Resouse通过byName的方式实现,如果找不到名字,则通过byType实现。如果两个都找不到就会报错
  • 执行顺序不同

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

//等价于:    <bean id="user" class="com.zhao.pojo.User"/>
//组件
@Component
public class User {
    public String name;
}

2、属性如何注入

public class User {
    //相当于:<property name="name" value="昭昭"/>
    @Value("昭昭")
    public String name;
}

3、衍生的注解

@component有几个衍生注解,我们在web开发中,会按照三层架构分层

  • dao 【@Repository】
  • service 【@Service】
  • controller 【@Controller】

这四个注解功能都是一样的,都是代表将某个类注册到spring容器中,装配bean!

4、自动装配

@autowired:自动装配类型,名字
  如果autowired不能唯一自动装配的属性,则需要通过@Qualifier(value="xx")
@Nullable  字段标记了这个注解,说明这个字段可以为null
@Resource  自动装配通过名字,类型

5、作用域

@Repository
@Scope("prototype")
public class UserDao {
}

6、小结

xml与注解:

  • xml更加万能,适用于任何场合,维护简单方便
  • 注解 不是自己的类使用不了,维护相对复杂

xml与注解最佳实践

  • xml用来管理bean
  • 注解只负责完成属性的注入
  • 我们在使用的过程中,只需要注意一个问题:必须要让注解生效,就需要开启注解的支持
<!--自动扫描包(指定要扫描的包,这个包下的注解就会生效)-->
    <context:component-scan base-package="com.zhao.pojo"/>
<!--    注解的驱动-->
    <context:annotation-config/>

9、使用java的方式配置Spring

我们现在要完全不使用Spring的xml配置了,全权交给java

javaConfig是Spring的一个子项目,在Spring4之后,成为了核心功能

实体类

//这个注解的意思:说明这个类被spring接管,注册在了容器中
@Component
@Data
public class User {
    //@Value 注入属性值
    @Value("zz")
    private String name;
}

配置类

//@Configuration 这个也会被spring注册到容器中,本来就是一个@Component
//@Configuration代表一个配置类,就和之前的beans.xml一样
@Configuration
@ComponentScan("com.zhao.pojo")
@Import(MyConfig2.class)
public class MyConfig {

    //注册一个bean,就相当于我们之前写的一个bean标签
    //这个方法的名字,就相当于bean标签中的id属性
    //这个方法的返回值,就相当于bean标签中的class属性
    @Bean
    public User getUser(){
        return new User();//就是返回要注入bean的对象
    }	 

}

测试

public class MyTest {
    @Test
    public void t1(){

        //如果完全使用了配置类的方法去做,我们就只能通过AnnotationConfig上下文来获取容器,通过配置类的class对象加载!
        ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
        User getUser = context.getBean("user", User.class);
        System.out.println(getUser.getName());
    }
}
public class MyTest {
    @Test
    public void t1(){

        //如果完全使用了配置类的方法去做,我们就只能通过AnnotationConfig上下文来获取容器,通过配置类的class对象加载!
        ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
        User getUser = context.getBean("getUser", User.class);
        System.out.println(getUser.getName());
    }
}

注意:这里使用了两种方法的获取了两个id,一个是user 另一个是getUser 虽然他们的结果相同,但是是通过不同的注解完成的

第一种:实在实体类上加注解@Componen)+在配置类加注解@ComponentScan(“com.zhao.pojo”)这两个注解完成,这里的bean的id就是user

第二种:在配置类上加注解,@Configuration+@Bean 再写对相应的方法获得bean的id为getUser对象。

这种纯java的配置方式,在springboot中随处可见!

10、代理模式

为什么要学习代理模式,因为这就是SpringAOP的底层【SpringAOP 和MVC 面试问】

代理模式的分类:

  • 静态代理
  • 动态代理

在这里插入图片描述

10.1、静态代理

角色分析:

  • 抽象角色:一般会使用接口或者抽象类来解决
  • 真实角色:被代理的角色
  • 代理角色:代理真实角色,代理真实角色后,我们会做一些附属操作
  • 客户:访问代理对象的人

代码步骤

1、接口

package com.zhao.demo01;
//租房
public interface Rent {
    void rent();
}

2、真实角色

package com.zhao.demo01;

public class Host implements Rent{
    public void rent() {
        System.out.println("房东租房");
    }
}

3、代理角色

package com.zhao.demo01;

public class Proxy implements Rent{
    private Host host;
    public Proxy() {
    }
    public Proxy(Host host) {
        this.host = host;
    }


    public void rent() {

        host.rent();
        seeHouse();
        het();
        fee();
    }
    //看房
    public void seeHouse(){
        System.out.println("中介带你看房");
    }
    //签合同
    public void het(){
        System.out.println("签合同");
    }

    public void fee(){
        System.out.println("收中介费");
    }
}

4、客户端访问角色

public class Client {
    public static void main(String[] args) {
        //房东要租房子
        Host host = new Host();
        //代理中介帮房东出租房子,但是会有一些附属操作
        Proxy proxy = new Proxy(host);

        //租客不用面对房东,直接找到中介即可
        proxy.rent();
    }
}

代理模式的好处

  • 可以是真实的角色的操作更加纯粹,不去关注一些公共的业务
  • 公共也就交给代理角色,实现了业务的分工
  • 公共业务发生扩展的时候,方便集中管理

缺点:

  • 一个真实角色就会产生一个代理角色,代码量翻倍,开发效率低

10.2、加深理解

例子:对于增删改查不同业务,我们需要加入一个日志的打印功能,但是在工作中,我们需要不改动原来的代码,但是要加入这个新的功能,我们就可以用代理模式,找一个代理类也实现这个接口,然后在这个类中创建原来的实体类对象作为属性,通过set方法或者是有参构造器实例化,之后重写接口的方法,把原来的方法引用进去,在实现和添加新的功能,这样我们就达到了我们的目的,并且没有破坏原来的代码。

代码:

接口:

package com.zhao.demo02;

public interface UserService {
    void add();
    void delete();
    void update();
    void query();
}

原来的实现类

package com.zhao.demo02;

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("查询了用户");
    }
}

代理类:

package com.zhao.demo02;

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+"方法");
    }
}

测试类

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

聊聊AOP

在这里插入图片描述

10.3、动态代理

  • 动态代理和静态代理角色一样
  • 动态代理的代理类是动态生成的,不是我们直接写好的
  • 动态代理分为两大类:基于接口的动态代理;基于类的动态代理
    • 基于接口的动态代理----JDK动态代理
    • 基于类:cglib
    • Java字节码:javassist

需要了解两个类:Proxy:代理 , Invokation:调用处理程序

自己理解:

动态代理就是省略我们自己手动的创建代理类,只需要实现一个InvocationHandler接口即可,此接口只有唯一的方法public Object invoke(Object proxy, Method method, Object[] args) 返回一个对象,本质是反射,proxy是代理类,我们不手动创建,就需要Proxy.newProxyInstance(this.getClass().getClassLoader(),
target.getClass().getInterfaces(),this);
}通过这个方法得到代理类,就不需要我们手动创建了;method是接口的方法,args是参数;

得到代理类也需要一些参数,就需要我们的接口,所以我们需要将接口通过set方法传进来。之后我们就可以在此代码上扩展我们的功能了,更加减少了代码量。

代码示例:

通用模板

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 {
        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();
        ProxyInvocationHandler handler = new ProxyInvocationHandler();
        handler.setTarget(userService);
        UserService proxy = (UserService) handler.getProxy();
        proxy.add();
    }
}

动态代理的好处:

  • 可以是真实的角色的操作更加纯粹,不去关注一些公共的业务
  • 公共也就交给代理角色,实现了业务的分工
  • 公共业务发生扩展的时候,方便集中管理
  • 一个动态代理类代理的是一个接口,一般对应一类业务
  • 一个动态代理类可以代理多个类,只要 是实现了同一个接口即可

11、AOP

11.1、什么是AOP

AOP(Aspect Oriented Programming)意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生泛型,利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。

在这里插入图片描述

11.2、Aop在Spring中的作用

提供声明式事务:允许用户自定义切面

  • 横切关注点 :跨越应用程序多个模块的方法或功能,即是,与我们业务逻辑无关的,但我们都需要关注的部分,就是横切关注点。如日志,安全,缓存,事务等等…
  • 切面(ASPECT):横切关注带你被模块化的特殊对象,即他是一个类
  • 通知(Advice):切面必须要完成的工作,即,他是类中的一个方法
  • 目标(Target):被通知的对象。
  • 代理(Proxy):向目标对象应用通知之后创建的对象。
  • 切入点(PointCut):切面通知执行的“地点”的定义。
  • 连接点(JoinPoint):与切入点匹配的执行点。

在这里插入图片描述

11.3、Spring实现AOP

织入包

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

方式一:使用SpringAPI接口

按照上图的逻辑,前置日志:

package com.zhao.log;


import org.springframework.aop.MethodBeforeAdvice;

import java.lang.reflect.Method;

public class Log implements MethodBeforeAdvice {
    //method:目标方法
    //args:参数
    //target:目标对象

    public void before(Method method, Object[] args, Object target) throws Throwable {

        System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
    }
}

后置日志:

import org.springframework.aop.AfterReturningAdvice;

import java.lang.reflect.Method;

public class AfterLog implements AfterReturningAdvice {

    //returnValue:返回值
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {

        System.out.println("执行了"+method.getName()+"方法,返回了:"+returnValue);
    }
}

spring配置文件:

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

<!--    注册bean-->
    <bean id="userService" class="com.zhao.service.UserServiceImpl"/>
    <bean id="log" class="com.zhao.log.Log"/>
    <bean id="after" class="com.zhao.log.AfterLog"/>
<!--方式一:使用原生的Spring API接口-->
<!--    配置AOP:需要导入aop的约束-->
    <aop:config>
<!--        切入点:  expression表达式
execution 要执行的位置! (*(修饰词) *(返回值) *(类名) *(方法名) *(参数))-->
        <aop:pointcut id="pointCut" expression="execution(* com.zhao.service.UserServiceImpl.*(..))"/>

<!--        执行环绕增加-->
        <aop:advisor advice-ref="log" pointcut-ref="pointCut"/>
        <aop:advisor advice-ref="after" pointcut-ref="pointCut"/>
    </aop:config>
</beans>

测试类:

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("springApplacation.xml");
        //动态代理代理的是接口
        UserService userService = context.getBean("userService", UserService.class);
        userService.add();
    }

输出结果:

在这里插入图片描述

自己理解:

完成上述前后置日志就跟上面的动态代理原理一样,但是有大佬封装了方法,我们只需要实现一些简单的接口和xml文件的标签配置文件,就可以轻松的达到目的,两个接口分别是这个方法执行之前,和执行之后,通过方法里面的参数我们可以知道,底层已经通过反射得到了这个方法执行前后所有的信息,日志只需要我们打印出来就行了,我们自己加一个简单的输出语句即可。接下来就是配置文件,首先要添加aop约束 通过aop:config标签进行配置,先配置pointCut切入点,(切入点: expression表达式
execution 要执行的位置! ( (修饰词) *(返回值) *(类名) *(方法名) *(参数))

通过这些确定切入点所在的类和方法参数返回值等等信息,然后通过执行环绕增加- 利用advisor标签 把我们通过bean注册的那些前后置日志类引入,在给他们切入点的id,就能定位到具体的方法,更加灵活方便,也不会改变原来的代码。

方式二:自定义实现AOP【主要是切面】

自定义一个类,写添加的方法

public class DiyPointCut {
    public void before(){
        System.out.println("方法执行前");
    }
    public void after(){
        System.out.println("方法执行后");
    }

}
<!--    方式二:自定义类-->
    <bean id="diy" class="com.zhao.diy.DiyPointCut"/>
    <aop:config>
<!--        切面-->
        <aop:aspect ref="diy">
            <aop:pointcut id="point" expression="execution(* com.zhao.service.UserServiceImpl.*(..))"/>
            <aop:before method="before" pointcut-ref="point"/>
            <aop:after method="after" pointcut-ref="point"/>
        </aop:aspect>
    </aop:config>

这种方法,虽然比第一种简单,但是就不能通过反射的到信息什么的了

方式三:注解

//方式三:使用注解实现AOP
@Aspect//标注这是一个切面
public class AnnotationPointCut {
    @Before("execution(* com.zhao.service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("=====方法执行前======");
    }
}
<!--    方式三:注解-->
    <bean id="annotationPointCut" class="com.zhao.diy.AnnotationPointCut"/>
<!--开启注解支持-->
    <aop:aspectj-autoproxy/>

12、整合Mybatis

12.1、回忆mybatis

  1. 编写实体类
  2. 编写核心配置文件
  3. 编写接口
  4. 编写mapper.xml
  5. 测试(可以写个工具类复用)

这里可能会遇到资源过滤的问题

在pom.xml配置如下就好了

    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

12.2、Mybatis-Spring

  1. 编写数据源
<!--    DataSource:使用Spring的数据源替换mybatis的配置  c3p0 dbcp druid
        我们这里的class使用spring提供的JDBC
-->
    <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=true&amp;useUnicode=true&amp;characterEncoding=utf-8"/>
        <property name="username" value="root"/>
        <property name="password" value="753951"/>
    </bean>
  1. SqlSessionFactory
<!--    sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
<!--        绑定mybatis配置文件-->
        <property name="configLocation" value="classpath:myConfig.xml"/>
        <property name="mapperLocations" value="classpath:com/zhao/mapper/*.xml"/>
    </bean>
  1. SqlSessionTemplate
    <!--    SqlSessionTemplate: 就是mybatis中的   sqlSession-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--        只能使用构造器注入sqlSessionFactory 因为源码里没有set方法注入-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>
  1. 需要给接口加实现类
public class UserMapperImpl implements UserMapper{

    //我们之前所有的操作,都是用sqlSession来执行,现在都是用SqlSessionTemplate来执行
    private SqlSessionTemplate sqlSession;

    public void setSqlSession(SqlSessionTemplate sqlSession) {
        this.sqlSession = sqlSession;
    }

    public List<User> query() {
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.query();
    }
}
  1. 将自己写的实现类,注入到Spring中
<?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">

    <import resource="spring-dao.xml"/>

    <bean id="userMapper" class="com.zhao.mapper.UserMapperImpl">
        <property name="sqlSession" ref="sqlSession"/>
    </bean>
    
</beans>
  1. 测试使用
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
        List<User> users = userMapper.query();
        for (User user : users) {
            System.out.println(user);
        }

方式二:

有一个SqlSessionDaoSupport的类,我们可以通过继承他,调用他的getsqlSession方法,获得一个sqlsession,这样就简化了我们创建spring中sqlSessionTemplate,并且不用通过set注入到容器里了,我们只需要创建一个类,然后在sqping配置文件中注册,以及将sqlSessionFactory的值引入就好了

public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper{
    public List<User> query() {

        return getSqlSession().getMapper(UserMapper.class).query();
    }
<bean id="userMapper2" class="com.zhao.mapper.UserMapperImpl2">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>

13、声明式事务

13.1、回顾事务

  • 要么都成功,要么都失败
  • 事务在项目开发中十分重要,涉及到数据的一致性问题,不能马虎。
  • 确保完整性和一致性

事务的ACID原则

  • 原子性
  • 一致性
  • 隔离性:多个业务可能操作同一个资源,防止数据损坏
  • 持久性:事务一点提交,无论系统发生什么问题,结果都不会被影响,被持久化的写到存储器中

13.2、spring中的事务管理

  • 声明式事务:AOP
  • 编程式事务:需要在代码中,进行事务管理

建议就是第一种直接切入,在spring中我们在配置文件中加入就好,或者加上注解。


<!--    配置声明式事务-->
    <bean id="transactionManger" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>



<!--    结合AOP实现事务的织入-->
<!--    配置事务通知:-->
    <tx:advice id="txAdvice" transaction-manager="transactionManger">
<!--        给哪些方法配置事务 tx:method -->
<!--        配置事务的传播特性:-->
        <tx:attributes>
            <tx:method name="add" propagation="REQUIRED"/>
            <tx:method name="delete"/>
            <tx:method name="update"/>
            <tx:method name="query" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

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

思考:

为什么需要事务?

  • 如果不配置事务,可能存在数据提交不一致的情况下

  • 如果我们不在spring中去配置声明式事务,我们就需要在带啊吗中手动配置
    port implements UserMapper{
    public List query() {

      return getSqlSession().getMapper(UserMapper.class).query();
    

    }




```xml
<bean id="userMapper2" class="com.zhao.mapper.UserMapperImpl2">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>

13、声明式事务

13.1、回顾事务

  • 要么都成功,要么都失败
  • 事务在项目开发中十分重要,涉及到数据的一致性问题,不能马虎。
  • 确保完整性和一致性

事务的ACID原则

  • 原子性
  • 一致性
  • 隔离性:多个业务可能操作同一个资源,防止数据损坏
  • 持久性:事务一点提交,无论系统发生什么问题,结果都不会被影响,被持久化的写到存储器中

13.2、spring中的事务管理

  • 声明式事务:AOP
  • 编程式事务:需要在代码中,进行事务管理

建议就是第一种直接切入,在spring中我们在配置文件中加入就好,或者加上注解。


<!--    配置声明式事务-->
    <bean id="transactionManger" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>



<!--    结合AOP实现事务的织入-->
<!--    配置事务通知:-->
    <tx:advice id="txAdvice" transaction-manager="transactionManger">
<!--        给哪些方法配置事务 tx:method -->
<!--        配置事务的传播特性:-->
        <tx:attributes>
            <tx:method name="add" propagation="REQUIRED"/>
            <tx:method name="delete"/>
            <tx:method name="update"/>
            <tx:method name="query" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

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

思考:

为什么需要事务?

  • 如果不配置事务,可能存在数据提交不一致的情况下
  • 如果我们不在spring中去配置声明式事务,我们就需要在带啊吗中手动配置
  • 事务在项目开发中十分重要,涉及到数据的一致性和完整性问题,不容马虎!
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值