Spring

Spring

1、Spring入门

1.1、简介

  • Spring框架是由于软件开发的复杂性而创建的
  • 2002年,首次推出了Spring框架的雏形:interface21框架
  • Spring框架在interface21框架基础上,经过重新设计,并不断丰富其内涵,于2004年3月24日发布了1.0正式版
  • Rod Johnson,Spring框架的创始人,同时也是SpringSource的联合创始人
  • Spring是面向切面编程(AOP)和控制反转(IOC)的容器框架
  • Spring理念:使现有的技术更加容易使用,本身是一个大杂烩,整合了现有的技术框架

官方文档:https://docs.spring.io/spring-framework/docs/current/reference/html/

Spring中文文档:https://www.docs4dev.com/docs/zh/spring-framework/5.1.3.RELEASE/reference/overview.html

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

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

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

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.3.12</version>
</dependency>

1.2、优点

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

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

1.3、组成

在这里插入图片描述


1.4、拓展

Spring的官网介绍:现代化的Java开发! 基于Spring开发

在这里插入图片描述

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

学习SpringBoot的前提,需要完全掌握Spring及SpringMVC

唯一弊端:SpringBoot发展太久之后,违背了原来的理念!配置十分繁琐!”

2、IOC理论推导

传统的开发方式:

在这里插入图片描述

  1. UserDao接口

    public interface UserDao {
        void getUser();
    }
    
  2. UserDaoImpl实现类

    public class UserDaoImpl implements UserDao {
        public void getUser() {
            System.out.println("默认获取用户的数据");
        }
    }
    
  3. UserService业务接口

    public interface UserService {
        void getUser();
    }
    
  4. UserServiceImpl业务实现类

    public class UserServiceImpl implements UserService {
        //程序是主动创建对象  导致用户的需求可能会影响我们原来的代码,
        // 我们需要根据用户的需求去修改源代码!如果程序的代码量十分大,
        // 修改一次的成本代价十分昂贵!
        private UserDao userDao=new UserDaoImpl();
        public void getUser() {
            userDao.getUser();
        }
    }
    

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

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

   private UserDao userDao;

    //利用set进行动态实现值的注入
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

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

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

在这里插入图片描述


2.1、IOC本质

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

在这里插入图片描述

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

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

3、HelloSpring

实体类

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 + '\'' +
                '}';
    }
}

beans.xml配置

   <!--使用Spring来创建对象,在Spring中这些都称为Bean
       类型 变量名=new 类型();
       Hello hello=new Hello();
       bean=对象  new Hello();
       id=变量名    class=new 的对象
       property 相当于给对象中的属性设置值
    -->
    <bean id="hello" class="com.gjy.pojo.Hello">
        <property name="str" value="Spring"></property>
    </bean>

测试

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是一种编程思想,由主动编程变成被动接收

可以通过new ClassPathXmlApplicationContext去了解底层源码

现在,要实现不同的操作,只需要在xml配置文件中进行修改,所谓的IOC就是: 对象由Spring来创建,管理,装配 !

4、IOC创建对象的方式

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

2.假如我们要使用有参构造创建对象

实体类

public class User {
    private String name;

    public User(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    public void show(){
        System.out.println("name="+name);
    }

第一种:下标赋值

<!--第一种,下标赋值!-->
<bean id="user" class="com.gjy.pojo.User">
    <constructor-arg index="0" value="Spring"></constructor-arg>
</bean>

第二种:通过类型创建,不建议使用

    <!--第二种,通过类型创建,不建议使用-->
    <bean id="user" class="com.gjy.pojo.User">
        <constructor-arg type="java.lang.String" value="Spring"></constructor-arg>
    </bean>

第三种: 直接通过参数名设置,推荐使用

    <!--第三种,直接通过参数名设置-->
    <bean id="user" class="com.gjy.pojo.User">
        <constructor-arg name="name" value="Spring"></constructor-arg>
    </bean>

测试类

public class MyTest {
    public static void main(String[] args) {
        //这一步就已经初始化容器中的所有对象
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        User user = (User) context.getBean("user");
        user.show();
    }
}

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

5、Spring配置

5.1、别名

<!--如果添加了别名,我们也可以通过别名获取到这个对象-->
<alias name="user" alias="user2"></alias>

5.2、Bean的配置

       <!--
          id  : bean 的唯一标识符,也就是相当于我们学的对象名
        class : bean 对象所对应的全限定名:包名 + 类型
        name :也是别名,而且name 可以同时取多个别名,可以用逗号,空格,分号分割-->
       <bean id="user" class="com.gjy.pojo.User" name="user3,user4 user5;user6">
        <constructor-arg name="name" value="Spring"></constructor-arg>
        <constructor-arg name="id" value="1"></constructor-arg>
       </bean>

5.3、import

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

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

  • A
  • B
  • C
  • applicationContext.xml

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

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

6、依赖注入(DI)

6.1、构造器注入

4.0中提到的有参构造和无参构造!

6.2、Set方式注入【重点】

  • 依赖注入 : Set注入 !
    • 依赖 : bean对象的创建依赖于容器 !
    • 注入 : bean对象中的所有属性由容器来注入 !

【环境搭建】

1.复杂类型

public class Address {
    private String address;

    public String getAddress() {
        return address;
    }

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

2.真实测试对象

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

3.beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="student" class="com.gjy.pojo.Student">
        <!-- 第一种,普通值注入,直接使用value-->
        <property name="name" value="李华"></property>
    </bean>
</beans>

4.测试类

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

完善注入信息

<?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.gjy.pojo.Address">
        <property name="address" value="浙江省杭州市"></property>
    </bean>
    <bean id="student" class="com.gjy.pojo.Student">
        <!-- 第一种,普通值注入,直接使用value-->
        <property name="name" value="李华"></property>
        <!--第二种,bean注入,ref -->
        <property name="address" ref="address"></property>
        <!-- 数组注入 -->
        <property name="books">
            <array>
                <value>红楼梦</value>
                <value>西游记</value>
                <value>水浒传</value>
                <value>三国演义</value>
            </array>
        </property>
        <!--List注入 -->
        <property name="hobbies">
            <list>
                <value>听歌</value>
                <value>看电影</value>
                <value>运动</value>
            </list>
        </property>
        <!-- map注入-->
        <property name="card">
            <map>
                <entry key="身份证" value="322234333333256665"></entry>
                <entry key="学号" value="111231413"></entry>
            </map>
        </property>
        <!-- set注入-->
        <property name="games">
            <set>
                <value>LOL</value>
                <value>CF</value>
            </set>
        </property>
        <!--null值注入-->
        <property name="wife">
            <null></null>
        </property>
        <!--Properties注入-->
        <property name="info">
            <props>
                <prop key="姓名">李杰</prop>
                <prop key="性别"></prop>
            </props>
        </property>
    </bean>
</beans>

6.3、拓展方式注入

我们可以使用p命名空间和c命名空间进行注入

使用:

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

    <!--p命名空间注入  可以直接注入属性的值-->
    <bean id="user" class="com.gjy.pojo.User" p:name="李华" p:age="18">
    </bean>

    <!--c命名空间注入  通过构造器注入:constructor-arg-->
    <bean id="user2" class="com.gjy.pojo.User" c:name="李华" c:age="19">
    </bean>
    
</beans>

测试:

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

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

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

6.4、bean的作用域(scope)

在这里插入图片描述

1.单例模式(Spring默认机制,在同一个bean中创建的实例都是同一个对象)

在这里插入图片描述

 <bean id="user2" class="com.gjy.pojo.User" c:name="李华" c:age="19" scope="singleton"/>

测试:

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

结果:

在这里插入图片描述


2.原型模式(每次从"容器"中get都会获得新的对象)

在这里插入图片描述

<bean id="user2" class="com.gjy.pojo.User" c:name="李华" c:age="19" scope="prototype"/>

测试:

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

结果:

在这里插入图片描述

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

7、Bean的自动装配

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

在Spring中有三种装配的方式

  • 在xml中显示的装配
  • 在java中显示装配
  • 隐式地自动装配bean [重点]

7.1、测试

1.环境搭建:一个人有两个宠物!

实体类

public class People {
    private Dog dog;
    private Cat cat;
    private String name;
}
public class Dog {
    public void shout(){
        System.out.println("汪!");
    }
}
public class Cat {
    public void shout(){
        System.out.println("喵!");
    }
}

7.2、byName自动装配

    <bean id="dog" class="com.gjy.pojo.Dog"/>
    <bean id="cat" class="com.gjy.pojo.Cat"/>

    <!--byName 会自动在容器上下文查找和自己对象set方法后面的值对应的bean id  -->
    <bean id="people" class="com.gjy.pojo.People" autowire="byName">
        <property name="name" value="李华"></property>
    </bean>

7.3、byType自动装配

    <bean id="dog" class="com.gjy.pojo.Dog"/>
    <bean id="cat" class="com.gjy.pojo.Cat"/>

    <!--byType : 会自动在容器上下文查找 和自己对象属性类型相同的bean  -->
    <bean id="people" class="com.gjy.pojo.People" autowire="byType">
        <property name="name" value="李华"></property>
    </bean>

小结 :

  • byName : 需要保证bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致!
  • byType : 需要正所有bean的class唯一,并且这个bean需要和自动注入的属性的类型一致!

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

使用注解须知:

  1. 导入约束 context约束

  2. 配置注解的支持 context:annotation-config/【注意加上:开启注解支持】

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

@Autowired

  1. 直接在属性上使用即可! 也可以在set方法上使用!

    public class People {
        @Autowired
        private Dog dog;
        @Autowired
        private Cat cat;
        private String name;
    }
    
  2. 使用 @Autowired注解后,我们可以不用编写Set方法了,因为它是通过反射获取的,但是前提是你这个自动装配的属性在IOC(Spring)容器中存在,且符合byName

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

     @Autowired(required = false) //如果显式的定义了required = false,那么这个对象可以为null,否则不能为空
     private Dog dog;
    
     public @interface Autowired {
        boolean required() default true;
    }
    
  4. 如果 @Autowired自动装配的环境比较复杂,无法通过一个注解完成的时候,可以使用**@Qualifier(value = “xxx”)**去配置@Autowired的使用,指定一个唯一的bean对象注入

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

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

小结: @Resource与@Autowired的区别

  • 都是用来自动装配的,都可以放在属性字段上
  • @Autowired通过byType的方式实现,而且必须要求这个对象存在!【常用】
  • @Resource默认通过byName的方式实现,如果找不到name,则通过byType实现!如果两个都找不到的情况下,就会报错【常用】
  • 执行顺序不同:@Autowired通过byType的方式实现,@Resource默认通过byName的方式实现

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

  2. 属性如何注入

    //@Component组件   等价于 <bean id="user" class="com.gjy.pojo.User"/>
    @Component
    public class User {
        // @Value 相当于  <bean id="user" class="com.gjy.pojo.User"><property name="name" value="李华"/>                            </bean>
        @Value("李华") 
        public String name;
    }
    
  3. 衍生的注解

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

    • dao 【@Repository】

    • service 【@Service】

    • controller 【@Controller】

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

  4. 自动装配

    @Autowired  @Resource   //具体参照7.1-7.4
    
  5. 作用域

    //@Component组件   等价于 <bean id="user" class="com.gjy.pojo.User"/>
    @Component
    @Scope("singleton") //作用域
    public class User {
        // @Value 相当于  <bean id="user" class="com.gjy.pojo.User"><property name="name" value="李华"/></bean>
        @Value("李华")
        public String name;
    }
    
  6. 小结

    xml配置与注解:

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

    xml配置与注解的最佳实践:

    • xml用来管理bean

    • 注解只完成属性的注入

    • 我们在使用的过程中,需要注意一个问题:想要注解生效,必须开启注解支持

      <context:component-scan base-package="com.gjy"/>
      <context:annotation-config/>
      

9、使用Java的方式配置Spring

完全不使用Spring的xml配置,全权交给Java来做

JavaConfig是Spring的一个子项目,在Spring 4之后,它成为了一个核心功能

在这里插入图片描述


实体类

@Component   //说明这个类被Spring接管了,注册到了容器中
public class User {
    @Value("李华") //属性注入值
    private String name;

    public String getName() {
        return name;
    }

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

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

配置类

//这个也会被Spring容器托管,注册到容器中,因为它本来就是一个@Component
//@Configuration 代表这是一个配置类,和ApplicationContext.xml是一样的
@Configuration
@ComponentScan("com.gjy.pojo")  //扫描包
@Import(MyConfig2.class)
public class MyConfig {

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

测试类

@Test
public void test(){
   //通过AnnotationConfigApplicationContext 上下文获取容器,通过配置类的class对象加载
   ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
   User user = (User) context.getBean("getUser");
   System.out.println(user.getName());
}

这种纯Java的配置方式 , 在SpringBoot中随处可见

10、代理模式

为什么要学代理模式 ? 因为这就是SpringAOP的底层 ! 【面试必问: SpringAOP 和 SpringMVC】

代理模式的分类

  • 静态代理
  • 动态代理

在这里插入图片描述


10.1、静态代理

角色分析 :

  • 抽象角色 : 共同完成的事情(租房) , 一般会用接口或者抽象类来解决
  • 真实角色 : 被代理的角色(房东)
  • 代理角色 : 代理真实角色(中介) , 代理真实角色后,我们一般会做一些附属操作
  • 客户 : 访问代理对象的人(你)

代码实现:

  1. 接口

    //租房:抽象角色
    public interface Rent {
        public void rent();
    }
    
  2. 真实角色

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

    //中介:代理角色
    public class Proxy implements Rent{
        private Landlord landlord;
    
        public Proxy(){
    
        }
        public Proxy(Landlord landlord) {
            this.landlord = landlord;
        }
    
        public void rent() {
            seeHouse();
            landlord.rent();
            contract();
            fare();
        }
        //看房
        public void seeHouse(){
            System.out.println("中介带你看房!");
        }
        //收中介费
        public void fare(){
            System.out.println("收中介费!");
        }
        //签合同
        public void contract(){
            System.out.println("签合同!");
        }
    }
    
  4. 客户端访问代理角色

    //客户:访问代理对象的人
    public class Client {
        public static void main(String[] args) {
            //房东要租房子
            Landlord landlord = new Landlord();
            //代理,中介帮房东租房子  但是,代理角色会有一些附属操作:签合同、收中介费
            Proxy proxy = new Proxy(landlord);
            //客户(租客)直接向中介租房即可
            proxy.rent();
        }
    }
    

代理模式的优点:

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

缺点 :

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

10.2、深入理解静态代理

代码实现

  1. 接口

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

    //真实对象
    public class UserServiceImpl implements UserService {
        public void add() {
            System.out.println("增加了一个用户");
        }
    
        public void delete() {
            System.out.println("删除了一个用户");
        }
    
        public void update() {
            System.out.println("修改了一个用户");
        }
    
        public void query() {
            System.out.println("查询了一个用户");
        }
        //改动原有的业务代码,在企业开发中是大忌!
    }
    
  3. 代理角色 实现公共业务,进行业务的分工

    public class UserServiceProxy implements UserService {
        private UserServiceImpl userService;
    
        public void setUserService(UserServiceImpl userService) {
            this.userService = userService;
        }
    
        public void add() {
            log("add");
            userService.add();
        }
    
        public void delete() {
            log("delete");
            userService.delete();
        }
    
        public void update() {
            log("update");
            userService.update();
        }
    
        public void query() {
            log("query");
            userService.query();
        }
        //日志方法
        public void log(String msg){
            System.out.println("使用了"+msg+"方法");
        }
    }
    
  4. 客户端访问代理角色

    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 : 代理, InvocationHandler : 调用处理程序

  • Proxy类提供了创建动态代理类的静态方法
  • InvocationHandler接口是proxy代理实例的调用处理程序实现的一个接口

动态代理的优点:

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

代码实现

  1. 接口

    public interface UserService {
        public void add();
        public void delete();
        public void update();
        public void query();
    }
    
  2. 真实对象

    //真实对象
    public class UserServiceImpl implements UserService {
        public void add() {
            System.out.println("增加了一个用户");
        }
    
        public void delete() {
            System.out.println("删除了一个用户");
        }
    
        public void update() {
            System.out.println("修改了一个用户");
        }
    
        public void query() {
            System.out.println("查询了一个用户");
        }
    }
    
  3. 动态代理工具类

    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    import java.lang.reflect.Proxy;
    
    //用这个类自动生成代理类
    public class ProxyInvocationHandler implements InvocationHandler {
    
        //被代理的接口
        private Object target;
    
        public void setTarget(Object target) {
            this.target = target;
        }
    
        //生成代理类
        public Object getProxy() {
            return Proxy.newProxyInstance(this.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
        }
    
        //处理代理实例,并返回结果
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            log(method.getName());
            //动态代理的本质,就是使用反射机制实现!
            Object result = method.invoke(target, args);
            return result;
        }
        public void log(String msg){
            System.out.println("调用了"+msg+"方法");
        }
    }
    
  4. 测试

    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.delete();
    
        }
    }
    

11、AOP

11.1、什么是AOP

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

在这里插入图片描述


11.2、AOP在Spring中的作用

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

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

在这里插入图片描述


在SpringAOP中,通过Advice定义横切逻辑,Spring中支持5种类型的Advice

在这里插入图片描述


即AOP在不改变原有代码的情况下去增加新的功能

11.3、使用Spring实现AOP

使用AOP,需要导入一个包

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

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

  1. 接口

    public interface UserService {
        public void add();
        public void delete();
        public void update();
        public void select();
    }
    
  2. 接口实现类

    public class UserServiceImpl implements UserService {
        public void add() {
            System.out.println("增加了一个用户");
        }
    
        public void delete() {
            System.out.println("删除了一个用户");
        }
    
        public void update() {
            System.out.println("修改了一个用户");
        }
    
        public void select() {
            System.out.println("查询了一个用户");
        }
    }
    
  3. 前置通知

    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()+"方法被执行了");
        }
    }
    
  4. 后置通知

    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);
        }
    }
    
  5. 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"
           xmlns:aop="http://www.springframework.org/schema/aop"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
            https://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/aop
            https://www.springframework.org/schema/aop/spring-aop.xsd
            ">
        <!--注册bean-->
        <bean id="userService" class="com.gjy.service.UserServiceImpl"/>
        <bean id="log" class="com.gjy.log.Log"/>
        <bean id="afterLog" class="com.gjy.log.AfterLog"/>
        <!--方式一:使用原生的Spring API接口-->
        <!--配置AOP  需要导入aop的约束-->
            <aop:config>
                <!--切入点   expression:表达式, execution(要执行的位置 ! * * * * *)-->
                <aop:pointcut id="pointcut" expression="execution(* com.gjy.service.UserServiceImpl.*(..))"/>
                <!--执行环绕增加-->
                <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
                <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
            </aop:config>
    </beans>
    
  6. 测试类

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

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

  1. 自定义类

    public class DiyPointCut {
        public void before(){
            System.out.println("======方法执行前======");
        }
        public void after(){
            System.out.println("======方法执行后======");
        }
    
    }
    
  2. 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"
           xmlns:aop="http://www.springframework.org/schema/aop"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
            https://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/aop
            https://www.springframework.org/schema/aop/spring-aop.xsd
            ">
        <!--注册bean-->
        <bean id="userService" class="com.gjy.service.UserServiceImpl"/>
        <bean id="log" class="com.gjy.log.Log"/>
        <bean id="afterLog" class="com.gjy.log.AfterLog"/>
        
        <!--方式二:自定义类-->
        <bean id="diy" class="com.gjy.diy.DiyPointCut"/>
        <aop:config>
            <!-- 自定义切面  ref 引用类-->
            <aop:aspect ref="diy">
                <!-- 切入点-->
                <aop:pointcut id="pointcut" expression="execution(* com.gjy.service.UserServiceImpl.*(..))"/>
                <!--通知-->
                <aop:before method="before" pointcut-ref="pointcut"></aop:before>
                <aop:after method="after" pointcut-ref="pointcut"></aop:after>
            </aop:aspect>
    
        </aop:config>
    
    </beans>
    
  3. 测试类

    注:接口和接口实现类同方式一

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

方式三:使用注解实现AOP

  1. 注解类

    //方式三:使用注解实现AOP
    @Aspect   //标注这是一个切面
    public class AnnotationPointCut {
        @Before("execution(* com.gjy.service.UserServiceImpl.*(..))")
        public void before() {
            System.out.println("======方法执行前======");
        }
    
        @After("execution(* com.gjy.service.UserServiceImpl.*(..))")
        public void after() {
            System.out.println("======方法执行后======");
        }
    
        //在环绕增强中,我们可以给定一个参数,代表我们要获取切入的点
        @Around("execution(* com.gjy.service.UserServiceImpl.*(..))")
        public void around(ProceedingJoinPoint jp) throws Throwable {
            System.out.println("环绕前");
            Signature signature = jp.getSignature();//获得签名
            System.out.println(signature);
            // 执行方法
            Object proceed = jp.proceed();
            System.out.println("环绕后");
            System.out.println(proceed);
    
        }
    
    }
    
  2. applicationContext.xml配置

        <!--方式三:注解实现AOP-->
        <bean id="annotationPointCut" class="com.gjy.diy.AnnotationPointCut"/>
        <!-- 开启注解支持-->
        <aop:aspectj-autoproxy/>
    
  3. 测试类

    注:接口和接口实现类同方式一

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

12、整合MyBatis

mybatis-spring中文文档地址:http://mybatis.org/spring/zh/index.html

步骤:

1、导入相关jar包

  • junit
  • mybatis
  • mysql数据库(mysql-connector-java)
  • spring相关 (spring-webmvc , spring-jdbc )
  • aop织入(aspectjweaver)
  • mybatis-spring 【new】
<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.24</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.7</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.3.13</version>
    </dependency>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.9.4</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.3.13</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.6</version>
    </dependency>
</dependencies>s

2、编写配置文件

3、测试

12.1、回顾MyBatis

  1. 编写实体类

    @Data
    public class User {
        private int id;
        private String name;
        private String pwd;
    }
    
  2. 编写核心配置文件

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    
    <!--configuration核心配置文件-->
    <configuration>
        <typeAliases>
            <package name="com.gjy.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&amp;
                    serverTimezone=Asia/Shanghai&amp;useSSL=true&amp;characterEncoding=UTF-8"/>
                    <property name="username" value="root"/>
                    <property name="password" value="123456"/>
                </dataSource>
            </environment>
        </environments>
        <mappers>
            <mapper class="com.gjy.mapper.UserMapper"></mapper>
        </mappers>
    </configuration>
    
  3. 编写接口

    public interface UserMapper {
        public List<User> selectUser();
    }
    
  4. 编写Mapper.xml

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    
    <mapper namespace="com.gjy.mapper.UserMapper">
    <select id="selectUser" resultType="user">
        select * from mybatis.user;
    </select>
    </mapper>
    
  5. 测试

     @Test
        public void testSelectUser() throws IOException {
            String resource="mybatis-config.xml";
            InputStream in = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory= new SqlSessionFactoryBuilder().build(in);
            SqlSession sqlSession = sqlSessionFactory.openSession(true);//true  开启事务提交
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            List<User> userList = mapper.selectUser();
            for (User user : userList) {
                System.out.println(user);
            }
        }
    

12.2、MyBatis-Spring

  1. 编写数据源

     <!--DataSource: 使用Spring的数据库替换Mybatis的配置 c3p0 dbcp druid
         我们这里使用Spring提供的JDBC: org.springframework.jdbc.datasource
         -->
        <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
            <property name="url" value="jdbc:mysql://localhost:3306/?mybatis&amp;
                    serverTimezone=Asia/Shanghai&amp;useSSL=true&amp;characterEncoding=UTF-8"/>
            <property name="username" value="root"/>
            <property name="password" value="123456"/>
        </bean>
    
  2. sqlSessionFactory

        <!--sqlSessionFactory-->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource" />
            <!--绑定Mybatis配置文件-->
            <property name="configLocation" value="classpath:mybatis-config.xml"></property>
            <!--绑定Mapper.xml-->
            <property name="mapperLocations" value="classpath:com/gjy/mapper/*.xml"></property>
        </bean>
    
  3. sqlSessionTemplate

        <!--SqlSessionTemplate就是我们用的sqlSession-->
        <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
            <!--只能使用构造器注入sqlSessionFactory,因为没有set方法-->
            <constructor-arg index="0" ref="sqlSessionFactory"/>
        </bean>
    
  4. 需要给接口加实现类

    接口

    public interface UserMapper {
        public List<User> selectUser();
    }
    

    实现类

    public class UserMapperImpl implements UserMapper {
        //我们所有操作,都使用sqlSession来执行,在原来,现在都使用SqlSessionTemplate
        private SqlSessionTemplate sqlSession;
    
        public void setSqlSession(SqlSessionTemplate sqlSession) {
            this.sqlSession = sqlSession;
        }
    
        public List<User> selectUser() {
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            List<User> userList = mapper.selectUser();
            return userList;
        }
    }
    
  5. 将自己写的实现类 , 注入到Spring中

    <bean id="userMapper" class="com.gjy.mapper.UserMapperImpl">
            <property name="sqlSession" ref="sqlSession"/>
    </bean>
    
  6. 测试

        @Test
        public void testSelectUser() throws IOException {
            ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
            UserMapperImpl userMapper =  context.getBean("userMapper", UserMapperImpl.class);
            List<User> userList = userMapper.selectUser();
            for (User user : userList) {
                System.out.println(user);
            }
        }
    

完整的spring-dao.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd
        ">
    <!--DataSource: 使用Spring的数据库替换Mybatis的配置 c3p0 dbcp druid
     我们这里使用Spring提供的JDBC: org.springframework.jdbc.datasource
     -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/?mybatis&amp;
                serverTimezone=Asia/Shanghai&amp;useSSL=true&amp;characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>
    <!--sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--绑定Mybatis配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
        <!--绑定Mapper.xml-->
        <property name="mapperLocations" value="classpath:com/gjy/mapper/*.xml"></property>
    </bean>
    <!--SqlSessionTemplate就是我们用的sqlSession-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <!--只能使用构造器注入sqlSessionFactory,因为没有set方法-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>

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

13、声明式事务

13.1、回顾事务

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

事务ACID原则 :

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

13.2、Spring中的事务管理

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

​ 代码实现:

  1. 实现类

    public class UserMapperImpl implements UserMapper {
        //我们所有操作,都使用sqlSession来执行,在原来,现在都使用SqlSessionTemplate
        private SqlSessionTemplate sqlSession;
    
        public void setSqlSession(SqlSessionTemplate sqlSession) {
            this.sqlSession = sqlSession;
        }
    
        public List<User> selectUser() {
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            List<User> userList = mapper.selectUser();
            int i = mapper.addUser(new User(7, "花花", "123456"));
            int i2 = mapper.deleteUserById(7);
            return userList;
        }
    
        public int addUser(User user) {
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            int i = mapper.addUser(user);
            return i;
        }
    
        public int deleteUserById(int id) {
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            int i = mapper.deleteUserById(id);
            return i;
        }
    }
    
  2. 在spring-dao.xml中配置事务

        <!--配置声明式事务-->
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource"/>
        </bean>
        <!--结合AOP实现事务的织入-->
        <!--配置事务的通知-->
        <tx:advice id="txAdvice" transaction-manager="transactionManager">
            <!--给那些方法配置事务-->
            <!--配置事物的传播特性 propagation  默认为REQUIRED(支持当前事务) -->
            <tx:attributes>
                <tx:method name="add" propagation="REQUIRED"/>
                <tx:method name="delete"/>
                <tx:method name="update"/>
                <tx:method name="select"/>
                <tx:method name="*"/>
            </tx:attributes>
        </tx:advice>
        <!-- 配置事务切入-->
        <aop:config>
            <aop:pointcut id="txPointCut" expression="execution(* com.gjy.mapper.*.*(..))"/>
            <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
        </aop:config>
    

    为什么需要事务?

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值