• Spring学习笔记


    一、Spring

    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

    • 官方下载地址:https://repo.spring.io/release/org/springframework/spring/

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

    
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-webmvcartifactId>
        <version>5.3.22version>
    dependency>
    
    
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-jdbcartifactId>
        <version>5.3.22version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    2、优点

    • Spring时一个开源的免费框架(容器)
    • Spring时一个清亮及的,非入侵传的框架
    • 控制反转(IOC),面向切面编程(AOP)
    • 支持事务处理,对框架整合的支持

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

    3、组成

    在这里插入图片描述

    4、拓展

    • 现代化的Java开发!就是面向spring的开发。
    • Spring Boot
      • 一个快速开发的脚手架
      • 基于SpringBoot可以快速的开发单个微服务
      • 约定大于配置
    • Spring Cloud
      • SpringCloud是基于SpringBoot实现的。

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

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

    二、IOC理论推导

    1、UserDao接口

    package com.jjl.dao;
    public interface UserDao {
        void getUser();
    }
    
    • 1
    • 2
    • 3
    • 4

    2、UserDaoImpl实现类

    package com.jjl.dao;
    public class UserDaoImpl implements UserDao{
        public void getUser(){
            System.out.println("默认获取用户的数据");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    3、UserService业务接口

    package com.jjl.service;
    public interface UserService {
        void getUser();
    }
    
    • 1
    • 2
    • 3
    • 4

    4、UserServiceImpl业务实现类

    public class UserServiceImpl implements UserService {
        private UserDao userDao = new UserDaoImpl();
        public void getUser() {
            userDao.getUser();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    5、测试

    public class MyTest {
        public static void main(String[] args) {
    
            //用户实际调用的是业务层,dao层他们不需要接触!
            UserService userService = new UserServiceImpl();
            userService.getUser();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    在这里插入图片描述

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

    我们使用一个Set接口实现,已经发生了革命性的变化!

    package com.jjl.service;
    import com.jjl.dao.UserDao;
    public class UserServiceImpl implements UserService{
        private UserDao userDao;
        public void setUserDao(UserDao userDao){
            this.userDao=userDao;
        }
        public void getUser() {
            userDao.getUser();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    这样无论有多少个实现类,都不用修改业务层,只需要给业务层传要调用的实现类就好,
    当需要横向扩展业务时,只需要写相应的业务实现类,然后去直接调用就好,不会修改程序整体架构。
    在这里插入图片描述
    Alt

    • 之前,程序是主动创建对象!控制权在程序猿手上!
    • 使用了set注入后,程序不再具有主动性,而是变成了被动的接收对象!

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

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

    采用XML方式配置Bean的时候,Bean的定义信息是和实现分离的,而采用注解的方式可以把两者合为一体,Bean的定义信息直接以注解的形式定义在实现类中,从而达到了零配置的目的。

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

    三、HelloSpring

    1、新建一个maven项目,编写实体类

    package com.jjl.pojo;
    
    public class Hello {
        private String str;
    
        public String getStr() {
            return str;
        }
    
        public void setStr(String str) {
            this.str = str;
        }
    
        @Override
        public String toString() {
            return "Hello{" +
                    "str='" + str + '\'' +
                    '}';
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    2、编写spring的xml配置文件

    
    <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="hello" class="com.jjl.pojo.Hello">
            <property name="str" value="Spring"/>
        bean>
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    3、测试

    import com.jjl.pojo.Hello;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    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());
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    在这里插入图片描述

    四、IOC创建对象的方式

    1、使用无参构造创建对象

    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

    2、假设哟啊使用有参构造创建

    在这里插入图片描述
    方法一:下标赋值

        <bean id="user" class="com.jjl.pojo.User">
            <constructor-arg index="0" value="xl"/>
        bean>
    
    • 1
    • 2
    • 3

    方法二: 通过参数类型创建,但是要保证实体类里没有相同类型的属性

    
        <bean id="user" class="com.jjl.pojo.User">
            <constructor-arg type="java.lang.String" value="xl"/>
        bean>
    
    • 1
    • 2
    • 3
    • 4

    方法三:通过参数名:

        <bean id="user" class="com.jjl.pojo.User">
            <constructor-arg name="name" value="xl"/>
        bean>
    
    • 1
    • 2
    • 3

    五、Spring配置

    1、别名

    在这里插入图片描述
    在这里插入图片描述

    2、bean的配置

       
        <bean id="user" class="com.jjl.pojo.User" name="user2 u1,u2">
            <constructor-arg name="name" value="xl"/>
        bean>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    3、import

    这个import。一般用于团队开发,它可以将多个配置文件,导入合并为一个。
    假设,现在项目中有多个人开发,这三个人负责不同的类开发,不同的类需要注册在不同的bean中,我们可以利用import将所有人的beans.xml合并为一个总的!

    • 张三
    • 李四
    • 王五
    • applicationContext.xml
      在这里插入图片描述
      使用的时候,直接使用总的配置就可以了。
      在这里插入图片描述

    六、依赖注入

    1、结构器注入

    2、set方法注入

    • 依赖注入:set注入
      • 依赖:bean对象的创建依赖于容器
      • 注入:bean对象中的所有属性,由容器来注入
        【环境搭建】
        1、复杂类型
    package com.jjl.pojo;
    public class Address {
        private String Address;
    
        public String getAddress() {
            return Address;
        }
    
        public void setAddress(String address) {
            Address = address;
        }
        @Override
        public String toString() {
            return "Address{" +
                    "Address='" + Address + '\'' +
                    '}';
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    2、真实测试对象

    package com.jjl.pojo;
    
    import java.util.*;
    
    public class Student {
        private String name;
        private Address address;
        private String[] book;
        private List<String> hobbys;
        private Map<String,String> card;
        private Set<String> games;
        private String wife;
        private Properties info;
    
        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[] getBook() {
            return book;
        }
    
        public void setBook(String[] book) {
            this.book = book;
        }
    
        public List<String> getHobbys() {
            return hobbys;
        }
    
        public void setHobbys(List<String> hobbys) {
            this.hobbys = hobbys;
        }
    
        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 String getWife() {
            return wife;
        }
    
        public void setWife(String wife) {
            this.wife = wife;
        }
    
        public Properties getInfo() {
            return info;
        }
    
        public void setInfo(Properties info) {
            this.info = info;
        }
    
        @Override
        public String toString() {
            return "Student{" +
                    "name='" + name + '\'' +
                    ", address=" + address +
                    ", book=" + Arrays.toString(book) +
                    ", hobbys=" + hobbys +
                    ", card=" + card +
                    ", games=" + games +
                    ", wife='" + wife + '\'' +
                    ", info=" + info +
                    '}';
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92

    3、beans.xml

    
    <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.jjl.pojo.Student">
            <property name="name" value="jjl"/>
        bean>
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    4、测试类

    import com.jjl.pojo.Student;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    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.getName());
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    5、完善注入信息

    
    <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.jjl.pojo.Address">
            <property name="address" value="四川成都"/>
        bean>
        <bean id="student" class="com.jjl.pojo.Student">
            
            <property name="name" value="jjl"/>
            
            <property name="address" ref="address"/>
            
            <property name="book">
                <array>
                    <value>《西游记》value>
                    <value>《红楼梦》value>
                    <value>《水浒传》value>
                    <value>《三国演义》value>
                array>
            property>
            
            <property name="hobbys">
                <list>
                    <value>听歌value>
                    <value>代码value>
                    <value>电影value>
                list>
            property>
            
            <property name="card">
                <map>
                    <entry key="身份证" value="123456789012345678"/>
                    <entry key="银行卡" value="123456789012345123"/>
                map>
            property>
            
            <property name="games">
                <set>
                    <value>LOLvalue>
                    <value>csvalue>
                    <value>BOBvalue>
                    <value>COCvalue>
                set>
            property>
            
            <property name="wife">
                <null/>
            property>
            
            <property name="info">
                <props>
                    <prop key="driver">18302020426prop>
                    <prop key="url">http://prop>
                    <prop key="username">xlprop>
                    <prop key="password">12341234prop>
                props>
            property>
        bean>
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62

    6、测试

    import com.jjl.pojo.Student;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    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.toString());
            /*
            Student{
            name='jjl',
            address=Address{Address='四川成都'},
            book=[《西游记》, 《红楼梦》, 《水浒传》, 《三国演义》],
            hobbys=[听歌, 代码, 电影],
            card={身份证=123456789012345678, 银行卡=123456789012345123},
            games=[LOL, cs, BOB, COC],
            wife='null',
            info={
                password=12341234, url=http://, driver=18302020426, username=xl
                }
            }
            * */
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    3、拓展方式注入

    P命名空间和c命名空间

    官方解释:
    https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-p-namespace
    在这里插入图片描述

    • 使用
      导入三方约束
      xmlns:p=“http://www.springframework.org/schema/p”
      xmlns:c=“http://www.springframework.org/schema/c”
      在这里插入图片描述

    • 测试
      User user = (User) context.getBean(“user”); == User user = context.getBean(“user”, User.class);
      在这里插入图片描述

    4、bean的作用域

    在这里插入图片描述
    1、单例模式(Spring默认机制)

    <bean id="user2" class="com.jjl.pojo.User" c:age="18" c:name="jjl" scope="singleton"/>
    
    • 1

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

    <bean id="user2" class="com.jjl.pojo.User" c:age="18" c:name="jjl" scope="prototype"/>
    
    • 1

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

    七、Bean的自动装配

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

    在spring中由三种装配的方式

    • 在xml中显示的配置
    • 在Java中显示配置
    • 隐式的自动装配bean【重点】

    1、测试

    不使用自动装配

        <bean id="cat" class="com.jjl.pojo.Cat"/>
        <bean id="dog" class="com.jjl.pojo.Dog"/>
        <bean id="people" class="com.jjl.pojo.People">
            <property name="name" value="xl"/>
            <property name="cat" ref="cat"/>
            <property name="dog" ref="dog"/>
        bean>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    2、ByName自动装配

        <bean id="cat" class="com.jjl.pojo.Cat"/>
        <bean id="dog" class="com.jjl.pojo.Dog"/>
        
        <bean id="people" class="com.jjl.pojo.People" autowire="byName">
            <property name="name" value="xl"/>
        bean>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    3、ByName自动装配

        <bean class="com.jjl.pojo.Cat"/>
        <bean class="com.jjl.pojo.Dog"/>
        
        <bean id="people" class="com.jjl.pojo.People" autowire="byType">
            <property name="name" value="xl"/>
        bean>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    小结:

    • byname的时候,需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方式的值一致!
    • byname的时候,需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性类型一致!

    4、使用注解实现自动装配

    jdk1.5支持的注解,spring2.5就开始支持了
    要使用注解须知:

    • 导入约束
      xmlns:context=“http://www.springframework.org/schema/context”
    • 配置注解的支持
      
      <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
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12

    @Autowired

    • 直接在属性上使用即可,也可以在set方法上使用!
    • 使用@Autowired我们可以不用在实体类中使用set方法了,前提是自动装配的属性在IOC(spring)容器中存在,且符合名字Byname!

    扩展:
    @Nullable: 字段标记了这个注释,说明这个字段可以为null

    public @interface Autowired {
        boolean required() default true;
    }
    
    • 1
    • 2
    • 3

    测试:

        //如果显示定义了Autowired的required属性false,说明这个对象可以为null,否则不允许为空
        @Autowired(required = false)
        private Cat cat;
        @Autowired
        private Dog dog;
        private String name;
    
        /*不允许为空*/
        public People(@Nullable String name) {
            this.name = name;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

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

    @Autowired
    @Qualifier(value = "cat111")
    private Cat cat;
    @Autowired
    @Qualifier(value = "dog222")//起别名
    private Dog dog;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
        <bean id="cat" class="com.jjl.pojo.Cat"/>
        <bean id="cat111" class="com.jjl.pojo.Cat"/>
        <bean id="dog222" class="com.jjl.pojo.Dog"/>
    
    • 1
    • 2
    • 3

    @Resource

        @Resource(name = "cat1")
        private Cat cat;
        @Resource
        private Dog dog;
    
    • 1
    • 2
    • 3
    • 4

    @Resource和@Autowired的区别:

    • 都是用来自动装配的,都可以放在属性字段上
    • @Autowired通过bytype的方式实现,
    • @Resource默认通过byname的方式实现,如果找不到名字,则通过bytype实现。
    • 执行顺序不同:Resource默认通过byname的方式实现,@Autowired通过bytype的方式实现。

    八、使用注解开发

    在spring4之后,要使用注解开发,必须要保证aop的包导入了
    在这里插入图片描述
    使用注解需要导入context约束,增加注解支持

    
    <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
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    1、bean

    
    <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:component-scan base-package="com.jjl.pojo"/>
        <context:annotation-config/>
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    2、属性如何注入

    package com.jjl.pojo;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Component;
    
    //@Component组件,这个注解等价于
    @Component
    public class User {  
        @Value("xl")//这个注解是给属性赋值,相当于public String name="xl",或者相当于
        public String name;
        public String pwd;
        //如果有set方法,@Value也可以放在set方法上
        @Value("123qwe")
        public void setPwd(String pwd) {
            this.pwd = pwd;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    测试

    public class MyTest {
        public static void main(String[] args) {
            ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
            User user = context.getBean("user", User.class);
            System.out.println(user.name);
            System.out.println(user.pwd);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    3、衍生的注解

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

    • dao【@Repository】
    • service【@Service】
    • controller【@Controller】
      【@Component】、【@Repository】、【@Service】、【@Controller】这四个注解功能是一样的,都是代表将某个类注册到spring中,装配Bean

    4、自动装配

    同上

    5、作用域

    在这里插入图片描述

    6、小结

    • xml与注解:
      • xml更加万能,适用于任何场景,维护简单方便
      • 注解不是自己类使用不了,维护相对复杂
    • xml与注解最佳实践
      • xml用来挂历bean;
      • 注解只负责完成属性的注入;
      • 我们在使用的过程中只需要注意一个问题,必须让注解生效,就需要开启注解的支持
        
            <context:component-scan base-package="com.jjl"/>
            <context:annotation-config/>`
        
        • 1
        • 2
        • 3

    九、使用Java的方式配置spring

    我们现在要我完全不适用spring的xml配置,全部交给java来做
    JavaConfig是Spring是的一个子项目,在spring4之后,他成为了一个核心功能

    实体类

    package com.jjl.pojo;
    
    
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Component;
    
    //这里这个注解的意思,就是说明这个类被spring接管了,注册到了容器中
    @Component
    public class User {
        private String name;
    
        public String getName() {
            return name;
        }
    
        @Value("jjl")//属性注入值
        public void setName(String name) {
            this.name = name;
        }
    
        @Override
        public String toString() {
            return "User{" +
                    "name='" + name + '\'' +
                    '}';
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    spring配置类

    package com.jjl.config;
    
    import com.jjl.pojo.User;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.Import;
    
    /*
    * 这个也会被spring容器托管,注册到容器中,因为它本来就是一个Component
    * @Configuration代表这是一个配置类,就和我们之前看的beans.xml是一样的
    * @Configuration和@ComponentScan("com.jjl.pojo")二选一即可
    * */
    @Configuration
    @ComponentScan("com.jjl.pojo")
    @Import(MyConfig2.class)//导入另一个类
    public class MyConfig {
        //注册一个bean,九相当于我们之前写的一个bean标签,
        //这个方法的名字,就相当于bean标签的id属性
        //这个方法的返回值,就相当于bean标签的class属性
        @Bean
        public User getUser(){
            return new User();//就是返回要注入到的bean对象
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    测试类

    import com.jjl.config.MyConfig;
    import com.jjl.pojo.User;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    
    public class MyText {
        public static void main(String[] args) {
            //如果完全使用了配置类方式去做,我们就只能通过AnnotationConfig上下文来获取容器,通过配置类的class对象加载
            ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
            User user = context.getBean("getUser", User.class);
            System.out.println(user.getName());
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    十、代理模式

    代理模式是springAOP的底层!【springAOP和springMVC】
    代理模式的分类:

    • 静态代理
    • 动态代理

    1、静态代理

    角色分析:

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

    代理步骤:
    1、接口

    package com.jjl.demo01;
    
    //租房
    public interface Rent {
        public void rent();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    2、真实角色

    package com.jjl.demo01;
    
    //房东
    public class Host implements Rent {
    
        @Override
        public void rent() {
            System.out.println("房东要出租房子");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    3、代理角色【使用构造器方式】

    package com.jjl.demo01;
    
    public class Proxy  implements Rent{
        private Host host;
    
        public Proxy() {
        }
    
        public Proxy(Host host) {
            this.host = host;
        }
    
        @Override
        public void rent() {
            host.rent();
            seeHouse();
            hetong();
            fare();
        }
    
        //看房
        public void seeHouse(){
            System.out.println("中介带你看房");
        }
    
        //合同
        public void hetong(){
            System.out.println("签租赁合同");
        }
    
        //收中介费
        public void fare(){
            System.out.println("收中介费");
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36

    4、客户端访问代理角色

    package com.jjl.demo01;
    
    public class Client {
        public static void main(String[] args) {
            //房东要租房子
            Host host = new Host();
            //代理,中介帮房东出租房子,但是呢,代理角色一般会有一些附加属性
            Proxy proxy = new Proxy(host);
    
            //你不用面对房东,直接找中介即可
            proxy.rent();
            //找中介看房
            proxy.seeHouse();
            //和中介签合同
            proxy.hetong();
            //付款给中介
            proxy.fare();
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    代理模式的好处

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

    缺点:

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

    2、加深理解

    测试场景:在不修改源业务层代码的情况下,给业务层类新增一些功能,这里可以使用代理

    • 接口类,有增删改查四个方法
      package com.jjl.demo02;
      
      public interface UserService {
          public void add();
          public void delete();
          public void update();
          public void query();
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
    • 源接口实现类
      package com.jjl.demo02;
      
      public class UserServiceImpl implements UserService{
          @Override
          public void add() {
              System.out.println("增加了一个用户");
          }
      
          @Override
          public void delete() {
              System.out.println("删除了一个用户");
          }
      
          @Override
          public void update() {
              System.out.println("修改了一个用户");
          }
      
          @Override
          public void query() {
              System.out.println("查询了一个用户");
          }
      }
      
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
    • 先需要给接口实现类的每一个方法里新增一个日志输出,不修改源代码。
      新增代理类【使用set方式】
      package com.jjl.demo02;
      
      public class UserServiceProxy implements UserService{
          private UserServiceImpl userService;
      
          public void setUserService(UserServiceImpl userService) {
              this.userService = userService;
          }
      
          @Override
          public void add() {
              log("add");
              userService.add();
      
          }
      
          @Override
          public void delete() {
              log("delete");
              userService.delete();
          }
      
          @Override
          public void update() {
              log("update");
              userService.update();
          }
      
          @Override
          public void query() {
              log("query");
              userService.query();
          }
          //加一个日志方法
          public void log(String msg){
              System.out.println("使用了"+msg+"方法");
          }
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
      • 33
      • 34
      • 35
      • 36
      • 37
      • 38

    3、动态代理

    • 动态代理和静态角色一样
    • 动态代理的代理类是动态生成的,不是我们直接写好的
    • 动态代理分为两大类:基于接口的动态代理,基于类的动态代理
      • 基于接口----JDK动态代理【我们使用这个】
      • 基于类:cglib
      • java字节码实现:javasist

    需要了解两个类:Proxy(代理),InvocationHandler:是代理实例的调用处理程序 实现的接口
    案例一:租房

    • 接口
      package com.jjl.demo03;
      
      //租房
      public interface Rent {
          public void rent();
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
    • 真实实现类
      package com.jjl.demo03;
      
      //房东
      public class Host implements Rent {
      
          @Override
          public void rent() {
              System.out.println("房东要出租房子");
          }
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
    • 动态代理类
      package com.jjl.demo03;
      
      import java.lang.reflect.InvocationHandler;
      import java.lang.reflect.Method;
      import java.lang.reflect.Proxy;
      
      //会用这个类自动生成代理类
      public class ProxyInvocationHandler implements InvocationHandler {
      
          private Rent rent;
      
          public void setRent(Rent rent) {
              this.rent = rent;
          }
          /*
          Foo f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(),
                new Class[] { Foo.class },
                handler)
          */
      
          //生成得到代理类
          public Object getProxy(){
              //Proxy.newProxyInstance:生成一个代理对象
              return Proxy.newProxyInstance(
                      //this.getClass().getClassLoader():加载类的位置
                      //rent.getClass().getInterfaces():表示代理的接口是哪一个
                      this.getClass().getClassLoader(), rent.getClass().getInterfaces(),this
              );
          }
      
          //处理代理实例,并返回结果
          @Override
          public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
              seeHouse();
              //动态代理的本质就是使用反射机制实现
              Object result = method.invoke(rent, args);
              fare();
              return result;
          }
      
          public void seeHouse(){
              System.out.println("中介带看房子");
          }
          public void fare(){
              System.out.println("收中介费");
          }
      }
      
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
      • 33
      • 34
      • 35
      • 36
      • 37
      • 38
      • 39
      • 40
      • 41
      • 42
      • 43
      • 44
      • 45
      • 46
      • 47
      • 48
    • 测试:
      package com.jjl.demo03;
      
      public class Client {
          public static void main(String[] args) {
              //真实角色
              Host host = new Host();
              //代理角色:现在没有
              ProxyInvocationHandler pih = new ProxyInvocationHandler();
              //通过调用程序处理角色,来处理我们要调用的接口对象
              pih.setRent(host);
      
              Rent proxy =(Rent) pih.getProxy();//这里的proxy就是动态生成的
              proxy.rent();
          }
      }
      
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16

    案例二:使用上面静态代理的User类

    • 万能的静态代理类

      package com.jjl.demo04;
      import java.lang.reflect.InvocationHandler;
      import java.lang.reflect.Method;
      import java.lang.reflect.Proxy;
      
      //会用这个类自动生成代理类
      //万能的动态代理类,只需要修改被代理的接口【target】、要新增内容的类要新增内容的类即可
      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
              );
          }
      
          //处理代理实例,并返回结果
          @Override
          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+"方法");
          }
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
      • 33
      • 34
      • 35
      • 36
      • 37
      • 38
      • 39
      • 40
    • 测试类

      package com.jjl.demo04;
      
      import com.jjl.demo02.UserService;
      import com.jjl.demo02.UserServiceImpl;
      
      public class Client {
          public static void main(String[] args) {
              //真实角色
              UserServiceImpl userService = new UserServiceImpl();
              //代理角色,不存在
              ProxyInvocationHandler pih = new ProxyInvocationHandler();
              pih.setTarget(userService);//设置要代理的对象
              //动态生成代理类
              UserService proxy = (UserService) pih.getProxy();
              proxy.add();
              proxy.delete();
      
          }
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
    • 测试结果
      在这里插入图片描述

    总结
    动态代理的好处

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

    十一、AOP

    1、 什么是AOP

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

    2 AOP在Spring中的作用

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

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

    SpringAOP中,通过Advice定义横切逻辑,Spring中支持5种类型的Advice:
    在这里插入图片描述
    在这里插入图片描述
    即AOP在不改变原有代码的情况下,去增加新的功能。

    3、使用spring实现Aop

    【重点】使用aop置入,需要导入一个依赖包!

            
            <dependency>
                <groupId>org.aspectjgroupId>
                <artifactId>aspectjweaverartifactId>
                <version>1.9.9.1version>
            dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    1、方式一:使用spring的API接口【主要试springapi接口实现】

    • 实体类接口
      package com.jjl.service;
      
      public interface UserService {
          public void add();
          public void delete();
          public void update();
          public void select();
      }
      
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
    • 接口实现类
      package com.jjl.service;
      
      public class UserServiceImpl implements UserService{
          @Override
          public void add() {
              System.out.println("增加了一个用户");
          }
      
          @Override
          public void delete() {
              System.out.println("删除了一个用户");
          }
      
          @Override
          public void update() {
              System.out.println("修改了一个用户");
          }
      
          @Override
          public void select() {
              System.out.println("查询到了一个用户");
          }
      }
      
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
    • 前置增强类
    package com.jjl.log;
    
    import org.springframework.aop.MethodBeforeAdvice;
    
    import java.lang.reflect.Method;
    
    public class Log implements MethodBeforeAdvice {
    
        //method:要执行的目标对象的方法
        //Object:参数
        //target:目标对象
        @Override
        public void before(Method method, Object[] args, Object target) throws Throwable {
            System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 后置增强类

      package com.jjl.log;
      import org.springframework.aop.AfterReturningAdvice;
      import java.lang.reflect.Method;
      public class AfterLog implements AfterReturningAdvice {
          //returnValue:返回值
          @Override
          public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
              System.out.println("执行了"+method.getName()+"返回结果为:"+returnValue);
          }
      }
      
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
    • 新建spring配置xml文件 ,并注册类, 实现aop环绕增强类切入 , 注意导入约束

      
      <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 id="userService" class="com.jjl.service.UserServiceImpl"/>
          <bean id="log" class="com.jjl.log.Log"/>
          <bean id="afterLog" class="com.jjl.log.AfterLog"/>
      
          
          
          <aop:config>
              
              <aop:pointcut id="pointcut" expression="execution(* com.jjl.service.UserServiceImpl.*(..))"/>
              
              
              <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
              <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
          aop:config>
      beans>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
    • 测试 在这里插入图片描述

    2、方式二:自定义类来实现AOP【只要是切面定义】

    • 延用方法一实现类
    • 新增自定义增强类,编写两个切入点的方法
      package com.jjl.diy;
      
      public class DiyPointCut {
          public void before(){
              System.out.println("====自定义=====方法执行前==========");
          }
          public void after(){
              System.out.println("====自定义=====方法执行后==========");
          }
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
    • 修改spring配置文件,并注册新增的增强类,配置AOP切入
    
    <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 id="userService" class="com.jjl.service.UserServiceImpl"/>
        
        <bean id="diy" class="com.jjl.diy.DiyPointCut"/>
        <aop:config>
            
            <aop:aspect ref="diy">
                
                <aop:pointcut id="point" expression="execution(* com.jjl.service.UserServiceImpl.*(..))"/>
                
                <aop:before method="before" pointcut-ref="point"/>
                <aop:after method="after" pointcut-ref="point"/>
            aop:aspect>
        aop:config>
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    3、方式三,使用注解实现

    • 延用方法一实现类
    • 新增自定义增强类,并注解标记相应切入点,还可以进一步处理切入点
      package com.jjl.diy;
      
      import org.aspectj.lang.ProceedingJoinPoint;
      import org.aspectj.lang.Signature;
      import org.aspectj.lang.annotation.After;
      import org.aspectj.lang.annotation.Around;
      import org.aspectj.lang.annotation.Aspect;
      import org.aspectj.lang.annotation.Before;
      
      //使用注解实现aop
      @Aspect  //标注这个类是一个切面
      public class AnnotationPointCut {
          @Before("execution(* com.jjl.service.UserServiceImpl.*(..))")
          public void before(){
              System.out.println("=====方法执行前=====");
          }
      
          @After("execution(* com.jjl.service.UserServiceImpl.*(..))")
          public void After(){
              System.out.println("====方法执行后====");
          }
      
          //在环绕增强中,可以给定一个参数,代表我们要获取处理切入点
          @Around("execution(* com.jjl.service.UserServiceImpl.*(..))")
          public void around(ProceedingJoinPoint jp) throws Throwable {
              System.out.println("环绕前");
              //执行方法
              jp.proceed();
              System.out.println("环绕后");
          }
      
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
    • 修改spring的xml配置文件
      
      <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 id="userService" class="com.jjl.service.UserServiceImpl"/>
          
          <bean id="annotationPointCut" class="com.jjl.diy.AnnotationPointCut"/>
          
          <aop:aspectj-autoproxy proxy-target-class="false"/>
      beans>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
    • 测试
      在这里插入图片描述

    十二、整合Mybatis

    步骤:
    1、导入相关jar包

    • junit
    • mybatis
    • mysql数据库
    • spring相关
    • aop织入
    • mybatis-spring【new】
    <dependencies>
            <dependency>
                <groupId>junitgroupId>
                <artifactId>junitartifactId>
                <version>4.13.2version>
                <scope>testscope>
            dependency>
            
            <dependency>
                <groupId>mysqlgroupId>
                <artifactId>mysql-connector-javaartifactId>
                <version>8.0.28version>
            dependency>
            <dependency>
                <groupId>org.mybatisgroupId>
                <artifactId>mybatisartifactId>
                <version>3.5.10version>
            dependency>
            <dependency>
                <groupId>org.springframeworkgroupId>
                <artifactId>spring-webmvcartifactId>
                <version>5.3.22version>
            dependency>
            
            
            <dependency>
                <groupId>org.springframeworkgroupId>
                <artifactId>spring-jdbcartifactId>
                <version>5.3.22version>
            dependency>
            
            <dependency>
                <groupId>org.aspectjgroupId>
                <artifactId>aspectjweaverartifactId>
                <version>1.9.9.1version>
            dependency>
            
            <dependency>
                <groupId>org.mybatisgroupId>
                <artifactId>mybatis-springartifactId>
                <version>2.0.7version>
            dependency>
            
    		<dependency>
    		    <groupId>org.projectlombokgroupId>
    		    <artifactId>lombokartifactId>
    		    <version>1.18.24version>
    		    <scope>providedscope>
    		dependency>
    
        dependencies>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51

    2、编写配置文件
    3、测试

    2、回忆mybatis

    1、编写实体类

    package com.jjl.pojo;
    
    import lombok.Data;
    
    @Data
    public class User {
        private int id;
        private String name;
        private String pwd;
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    2、编写核心配置文件

    <?xml version="1.0" encoding="UTF8" ?>
    <!DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <!--configuration核心配置文件-->
    <configuration>
        <typeAliases>
            <package name="com.jjl.pojo"/>
        </typeAliases>
    
        <environments default="development">
            <environment id="development">
                <transactionManager type="JDBC"/>
                <dataSource type="POOLED">
                    <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                    <property name="url" value="jdbc:mysql://localhost:3306/mybatis?userSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
                    <property name="username" value="root"/>
                    <property name="password" value="1234qwer"/>
                </dataSource>
            </environment>
        </environments>
        <mappers>
    <!--        <mapper class="com.jjl.mapper.UserMapper"/>-->
            <package name="com.jjl.mapper"/>
        </mappers>
    </configuration>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    3、编写接口

    package com.jjl.mapper;
    import com.jjl.pojo.User;
    import java.util.List;
    public interface UserMapper {
        public List<User> selectUser();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    4、编写Mapper.xml

    
    DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    <mapper namespace="com.jjl.mapper.UserMapper">
        <select id="selectUser" resultType="user">
            select * from user;
        select>
    mapper>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    5、测试

    import com.jjl.mapper.UserMapper;
    import com.jjl.pojo.User;
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    import org.junit.Test;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.List;
    
    public class MyTest {
        @Test
        public void test() throws IOException {
            String resources = "mybatis-config.xml";
            InputStream in= Resources.getResourceAsStream(resources);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
            SqlSession sqlSession = sqlSessionFactory.openSession(true);
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            List<User> userList = mapper.selectUser();
            for (User user : userList) {
                System.out.println(user.toString());
            }
            sqlSession.close();
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    注意:
    1、将两个xml文件中头部处的"UTF-8"改为“UTF8"
    2、在porm.xml中添加

    <build>
            <resources>
                <resource>
                    <directory>src/main/resourcesdirectory>
                    <includes>
                        <include>**/*.propertiesinclude>
                        <include>**/*.xmlinclude>
                    includes>
                    <filtering>truefiltering>
                resource>
                <resource>
                    <directory>src/main/javadirectory>
                    <includes>
                        <include>**/*.propertiesinclude>
                        <include>**/*.xmlinclude>
                    includes>
                    <filtering>truefiltering>
                resource>
            resources>
        build>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    2、Mybatis-Spring

    官网:http://mybatis.org/spring/zh/index.html
    在这里插入图片描述
    注意匹配版本
    1、创建spring-dao.xml文件,编写数据源配置、sqlSessionFactory、sqlSessionTemplate

    
    <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 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?userSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
            <property name="username" value="root"/>
            <property name="password" value="1234qwer"/>
        bean>
    
        
        <bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="DataSource"/>
            
            <property name="configLocation" value="classpath:mybatis-config.xml"/>
            
            <property name="mapperLocations" value="classpath:com/jjl/mapper/*.xml"/>
        bean>
    
        
        <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
            
            <constructor-arg index="0" ref="SqlSessionFactory"/>
        bean>
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33

    2、调整mybatis配置文件mybatis-config.xml,只保留configuration核心配置文件别名配置。【可以将配这个配置也移交给spring-dao.xml文件】

    
    DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    
    <configuration>
        <typeAliases>
            <package name="com.jjl.pojo"/>
        typeAliases>
    configuration>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    3、编写接口实现类,主要实现数据库的相关操作

    package com.jjl.mapper;
    import com.jjl.pojo.User;
    import org.mybatis.spring.SqlSessionTemplate;
    import java.util.List;
    
    public class UserMapperImpl  implements UserMapper{
        /*我们的所有操作,都使用sqlsession来执行,现在都使用sqlsessionTemplate*/
        private SqlSessionTemplate sessionTemplate;
    
        public void setSessionTemplate(SqlSessionTemplate sessionTemplate) {
            this.sessionTemplate = sessionTemplate;
        }
    
        public List<User> selectUser(){
            UserMapper mapper = sessionTemplate.getMapper(UserMapper.class);
            return mapper.selectUser();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    4、ApplicationContext.xml文件,将实现类注入到spring中

    
    <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-dao.xml"/>
        
        <bean id="userMapper" class="com.jjl.mapper.UserMapperImpl">
            <property name="sessionTemplate" ref="sqlSession"/>
        bean>
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    5、测试

    import com.jjl.mapper.UserMapper;
    import com.jjl.pojo.User;
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class MyTest {
        @Test
        public void test() {
            ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
            UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
            for (User user : userMapper.selectUser()) {
                System.out.println(user);
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    6、目录:
    在这里插入图片描述
    扩展:方式二
    让接口实现类继承SqlSessionDaoSupport,就可以让实现类更加简化

    package com.jjl.mapper;
    import com.jjl.pojo.User;
    import org.mybatis.spring.support.SqlSessionDaoSupport;
    import java.util.List;
    
    public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper{
        public List<User> selectUser() {
    //        SqlSession sqlSession = getSqlSession();
    //        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    //        return mapper.selectUser();
            /*精简成一行*/
            return getSqlSession().getMapper(UserMapper.class).selectUser();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    ApplicationContext.xml文件,将实现类注入到spring中

        
        <bean id="userMapper2" class="com.jjl.mapper.UserMapperImpl2">
            <property name="sqlSessionFactory" ref="SqlSessionFactory"/>
        bean>
    
    • 1
    • 2
    • 3
    • 4

    测试:

    十三、声明式事务

    1、回顾事务

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

    事务得ACID原则:

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

    2、spring中的事务管理

    • 声明式事务:交由容器管理事务(AOP)
    • 编程式事务:需要再代码中,进行事务的管理
      在这里插入图片描述

    Spring在不同的事务管理API之上定义了一个抽象层,使得开发人员不必了解底层的事务管理API就可以使用Spring的事务管理机制。Spring支持编程式事务管理和声明式的事务管理。

    编程式事务管理

    • 将事务管理代码嵌到业务方法中来控制事务的提交和回滚
    • 缺点:必须在每个事务操作业务逻辑中包含额外的事务管理代码

    声明式事务管理

    • 一般情况下比编程式事务好用。
    • 将事务管理代码从业务方法中分离出来,以声明的方式来实现事务管理。
    • 将事务管理作为横切关注点,通过aop方法模块化。Spring中通过Spring AOP框架支持声明式事务管理。

    添加增删的接口

    package com.jjl.mapper;
    
    import com.jjl.pojo.User;
    
    import java.util.List;
    
    public interface UserMapper {
        public List<User> selectUser();
    
        //添加一个用户
        public int addUser(User user);
        //删除一个用户
        public int deleteUser(int id);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    编写mybatis的sql

    
    DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    <mapper namespace="com.jjl.mapper.UserMapper">
        <select id="selectUser" resultType="user">
            select * from user;
        select>
        
        <insert id="addUser" parameterType="user">
            insert into user (id, name,pwd) values (#{id}, #{name},#{pwd});
        insert>
    
        <delete id="deleteUser" parameterType="int">
            delete from user where id=#{id}
        delete>
    mapper>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    编写接口实现类

    package com.jjl.mapper;
    
    import com.jjl.pojo.User;
    import org.mybatis.spring.support.SqlSessionDaoSupport;
    
    import java.util.List;
    
    public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper{
        public List<User> selectUser() {
            User user = new User(11, "小明", "1234");
            UserMapper mapper = getSqlSession().getMapper((UserMapper.class));
            addUser(user);
            deleteUser(10);
            return mapper.selectUser();
        }
        public int addUser(User user) {
            return getSqlSession().getMapper(UserMapper.class).addUser(user);
        }
    
        public int deleteUser(int id) {
            return getSqlSession().getMapper(UserMapper.class).deleteUser(id);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    在spring-dao.xml中配置事务,注意引入tx

    
    <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"
           xmlns:tx="http://www.springframework.org/schema/tx"
           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
            http://www.springframework.org/schema/tx
            https://www.springframework.org/schema/tx/spring-tx.xsd">
    
        
        <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?userSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
            <property name="username" value="root"/>
            <property name="password" value="1234qwer"/>
        bean>
    
        
        <bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="DataSource"/>
            
            <property name="configLocation" value="classpath:mybatis-config.xml"/>
            
            <property name="mapperLocations" value="classpath:com/jjl/mapper/*.xml"/>
        bean>
    
        
        <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
            
            <constructor-arg index="0" ref="SqlSessionFactory"/>
        bean>
    
        
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="DataSource"/>
        bean>
    
        
        
        <tx:advice id="txAdvice" transaction-manager="transactionManager">
            
            
            <tx:attributes>
                <tx:method name="add" propagation="REQUIRED"/>
                <tx:method name="delete" propagation="REQUIRED"/>
                <tx:method name="query" read-only="true"/>
                <tx:method name="update" propagation="REQUIRED"/>
                
                <tx:method name="*" propagation="REQUIRED"/>
            tx:attributes>
        tx:advice>
    
        
        <aop:config>
            <aop:pointcut id="txPointCut" expression="execution(* com.jjl.mapper.*.*(..))"/>
            <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut" />
        aop:config>
    
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63

    思考:

    为什么需要事务?

    • 如果不配置事务,可能存在数据提交不一致的情况;
    • 如果我们不在Spring中去配置声明式事务,我们就需要在代码中手动配置事务!
    • 事务在项目的开发中十分重要,涉及到数据的一致性和完整性问题,不容马虎!
  • 相关阅读:
    C#使用NPOI库实现Excel的导入导出操作——提升数据处理效率的利器
    yolo-nas使用教程
    【产品经理修炼之道】- 企业内部礼品库存管理系统设计(从需求到上线)B端
    qrcode.min.js下载
    软件方法——业务建模和需求(好书推荐)
    @EqualsAndHashCode注解!!!
    贪吃蛇(C语言版)链表实现
    计算图片中两个任意形状多边形相交部分的大小
    C++程序设计
    一文搞懂this指向
  • 原文地址:https://blog.csdn.net/qq_43427354/article/details/126365581