Spring

狂神说JAVA学习笔记

Spring

简介

  • Spring:春天,给软件行业带来了春天!
  • 2002,首次推出Spring框架的雏形:interface21框架
  • 2004.03.24Spring框架以interface21框架为基础,经过重写设计,并不断丰富其内涵,发布1.0正式版
  • Rod Johnson,Spring Framework创始人,他是悉尼大学的博士,然而他的专业不是计算机,而是音乐学。
  • Spring理念:使现有的技术更加容易使用,整合了现有的技术框架!

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

官方下载地址:https://spring.io/projects/spring-framework#overview

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

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

优点

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

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

组成

image-20210511151132816

扩展

在Spring官网:现代化的JAVA开发!说白了就是基于Spring开发!

image-20210429101307396

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

IOC理论推导

  1. UserDao接口
public interface UserDao {
    public void getUser();
}
  1. UserDaoImpl实现类

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

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

    
    public class UserServiceImpl implements UserService {
        //变更UserDao的实现则此处就需要变更实现类
        private UserDao userDao=new UserDaoImpl();
    
        public void getUser() {
            userDao.getUser();
        }
    }
    

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

//若增加一个UserDaoMySQLImpl
public class UserDaoMySQLImpl implements UserDao {
    public void getUser() {
        System.out.println("MySQL获取用户的数据!");
    }
}
//则UserServiceImpl变更为
public class UserServiceImpl implements UserService {
    private UserDao userDao=new UserDaoMySQLImpl();

    public void getUser() {
        userDao.getUser();
    }
}
//每次变更都需要主动更新实现类的创建

我们利用一个set接口实现。已经发生革命性的变化!

private UserDao userDao;

public class UserServiceImpl implements UserService {
    private UserDao userDao;
    
    //利用set动态实现值的注入
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public void getUser() {
        userDao.getUser();
    }
}
//此时不需要业务层任何的变动,只有在使用的地方用户进行setUserDao即可
  • 之前程序主动创建对象!控制权在程序员手中!
  • 使用了set注入之后,程序不再具有主动性,而是变成了被动的接受对象!

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

IOC本质

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

image-20210429111837615

IOC是Spring框架的核心内容,使用多种方式完美的实现了IOC,可以使用XML配置,也可以使用注解,新版本的Spring也可以零配置实现IOC。

Spring的容器在初始化的时候先读取配置文件,根据配置文件或元数据创建与组织对象存入容器中,程序使用时在从IOC容器中取出需要的对象。

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

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

HelloSpring

1 编写实体类

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

2 编写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="hello" class="com.hing.pojo.Hello">
        <property name="str" value="hing"></property>
    </bean>
</beans>

3 编写测试类

public class MyTest {
    public static void main(String[] args) {
        //获取Spring的上下文对象,解析beans.xml文件,生成管理相应bean对象
        ApplicationContext context =
                new ClassPathXmlApplicationContext("beans.xml");
        //我们的对象现在都是在Spring中进行管理了,我们要使用直接去里边取就可以了!
        //参数为Spring配置文件bean的id
        Hello hello =(Hello) context.getBean("hello");
        System.out.println(hello.toString());
    }
}

Hello对象是谁创建的?Hello对象的属性是谁设置的?

hello对象是由Spring创建的,hello对象的属性是由Spring设置的。

这个过程就叫控制反转:

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

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

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

IOC是一种编程思想,由主动的编程变成被动的接受。

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

IOC创建对象的方式

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

  2. 使用有参构造创建对象:

    1. 下标赋值

      <bean id="user" class="com.hing.pojo.User">
          <constructor-arg index="0" value="hing"></constructor-arg>
      </bean>
      
    2. 类型赋值

      <bean id="user" class="com.hing.pojo.User">
          <constructor-arg type="java.lang.String" value="恒影"></constructor-arg>
      </bean>
      
    3. 参数名赋值

      <bean id="user" class="com.hing.pojo.User">
          <constructor-arg name="name" value="ying"></constructor-arg>
      </bean>
      

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

Spring配置

别名

<alias name="user" alias="user01"/>

Bean配置

<!--
    id:bean的唯一标识符,也就是对象名称
    class:bean对象所对应的全限定名称:包名+类名
    name:也是别名,而且name可以同时取多个名
-->
<bean id="userT" class="com.hing.pojo.UserT" name="t t1,t2;t3"/>

import

一般用于团队开发使用,他可以将多个配置文件导入合并为1个。多个人文件为beans1.xml,beans2.xml,beans3.xml,利用import合并所有的文件汇总到applicationContext.xml中

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

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

依赖注入

构造器注入

set方式注入【重点】

依赖注入:set注入

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

【环境搭建】

  1. 复杂类型

    public class Address {
        private String address;
    }
    
  2. 真实测试对象

    public class Student {
        private String name;
        private Address address;
        private String[] books;
        private List<String> hobbys;
        private Map<String,String> cards;
        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.hing.pojo.Student">
            <!--第一种 普通值注入-->
            <property name="name" value="ying"/>
        </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());
        }
    }
    
  5. 完善注入信息

    <!--数组-->
    <property name="books">
        <array>
            <value>语文</value>
            <value>数学</value>
            <value>英语</value>
        </array>
    </property>
    
    <!--List-->
    <property name="hobbys">
        <list>
            <value>画画</value>
            <value>听歌</value>
            <value>打篮球</value>
        </list>
    </property>
    
    <!--Map-->
    <property name="cards" >
        <map>
            <entry key="身份证" value="2123243423413124"/>
            <entry key="银行卡" value="21111111111111111111"/>
        </map>
    </property>
    
    <!--Set-->
    <property name="games">
        <set>
            <value>LOL</value>
            <value>COC</value>
            <value>BOB</value>
        </set>
    </property>
    
    <!--null-->
    <property name="wife">
        <null></null>
    </property>
    
    <!--Properties-->
    <property name="info">
        <props>
            <prop key="driver">202111111</prop>
            <prop key="url">http:asdasdasd</prop>
            <prop key="name">小米</prop>
            <prop key="password">202111111</prop>
        </props>
    </property>
    

拓展方式注入

可以使用P命名空间及C命名空间进行注入

官方解释:

image-20210429164055152

使用:

<?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命名空间注入,可以直接注入属性的值:properties-->
    <bean id="user" class="com.hing.pojo.User" p:name="ying" p:age="17"/>

    <!--C命名空间注入,通过构造器注入:constructs-args-->
    <bean id="user1" class="com.hing.pojo.User" c:name="hing" c:age="16"/>

</beans>

测试:

@Test
public void test01(){
    ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");

    User user=context.getBean("user",User.class);
    System.out.println(user.toString());

    User user1=context.getBean("user1",User.class);
    System.out.println(user1.toString());
}

注意点:P命名和C命名不能直接使用,需要导入xml约束

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

bean的作用域

image-20210429170730348

  1. 单例模式(Spring默认机制)

     <bean id="user1" class="com.hing.pojo.User" c:name="hing" c:age="16" scope="singleton"/>
    
  2. 原型模式(每次从容器中get的时候都会产生一个新对象!)

    <bean id="accountService" class="com.something.DefaultAccountService" scope="prototype"/>
    
  3. 其余的request、session、application这些只能在web开发中使用到!

Bean的自动装配

自动装配是Spring满足bean的依赖的一种方式!

Spring会在上下文中自动寻找,并自动给bean装配属性!

在Spring有三种自动装配的方式:

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

测试

环境搭建:一个人两个宠物

ByName自动装配

<bean id="dog" class="com.hing.pojo.Dog"/>
<bean id="cat" class="com.hing.pojo.Cat"/>
<bean id="people" class="com.hing.pojo.People" autowire="byName">
    <property name="name" value="hing"/>
</bean>

ByType自动装配

<bean class="com.hing.pojo.Dog"/>
<bean class="com.hing.pojo.Cat"/>
<!--
    byName:会自动在容器上下文查找,和自己对象set方法后边的值对应的bean id
    byType:会自动在容器上下文查找,和自己对象属性类型相同的bean
-->
<bean id="people" class="com.hing.pojo.People" autowire="byType">
    <property name="name" value="hing"/>
</bean>

小结:

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

使用注解自动装配

jdk1.5支持注解,Spring2.5就支持注解了。

The introduction of annotation-based configuration raised the question of whether this approach is “better” than XML.

要使用注解须知:

  1. 导入约束:context约束

  2. 配置注解的支持:context:annotation-config/

    	<?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
            https://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            https://www.springframework.org/schema/context/spring-context.xsd">
    
        <context:annotation-config/>
    
    </beans>
    
  3. @Autowired直接在属性上使用即可,也可以在set方法上使用

    使用Auto wired可以不用编写set方法了,前提是你这个自动装配的属性在IOC(Spring)中存在,且符合名字byName!

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

public class People {
    @Autowired
    @Qualifier(value = "dog1111")
    private Dog dog;
    
    @Autowired
    @Qualifier(value = "cat1111")
    private Cat cat;
    private String name;
}
<?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/>

    <bean id="dog11" class="com.hing.pojo.Dog"/>
    <bean id="dog1111" class="com.hing.pojo.Dog"/>
    <bean id="cat11" class="com.hing.pojo.Cat"/>
    <bean id="cat1111" class="com.hing.pojo.Cat"/>
    <bean id="people" class="com.hing.pojo.People"/>

</beans>

​ @Resource注解

@Resource(name = "dog11")
private Dog dog;

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

小结:

@Resource与@Autowired的区别:

  • 都是用来自动装配的,都可以放在属性字段上
  • @Autowired默认是通过byType方式实现,而且必须要求这个对象存在
  • @Resource默认通过byName的方式实现,如果找不到名字通过byType实现!
  • 执行顺序不同:@Autowired先byType再byName,@Resource先byName再byType。

使用注解开发

在Spring4.0之后,要使用注解开发,必须要保证AOP包的导入

image-20210430170049663

使用注解需要增加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:component-scan base-package="com.hing.pojo"/>
    <context:annotation-config/>

</beans>
  1. bean

    //等价于<bean id="user" class="com.hing.pojo.User"/>
    //@Component 组件
    @Component
    public class User {
        
    }
    
  2. 属性如何注入

    @Component
    public class User {
        public String name;
    
        //等价于<property name="name" value="Hing"/>
        @Value("Hing")
        public void setName(String name) {
            this.name = name;
        }
    }
    
  3. 衍生的注解

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

    • dao [@Repository]
    • service[@Service]
    • controller[@Controller]

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

  4. 自动装配

    -@Autowired:自动装配 -类型- 名字,如果不能唯一自动装配上属性则需要
        @Qualifier(value = "bean id")
    -@Resource:自动装配-名字-类型
    -@Nullable:字段标记这个注解说明这个字段可以为空
    
  5. 作用域

    @Component
    @Scope("singleton")  //作用域
    public class User {
        public String name;
    
        //等价于<property name="name" value="Hing"/>
        @Value("Hing")
        public void setName(String name) {
            this.name = name;
        }
    }
    
  6. 小结

    xml与注解:

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

    xml与注解的最佳实践:

    • xml用来管理bean

    • 注解只负责完成属性的注入!

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

      <!-- 指定要扫描的包,整个包下的注解就会生效-->
      <context:component-scan base-package="com.hing"/>
      <context:annotation-config/>
      

使用Java的方式配置Spring

不使用spring的xml配置,全权交给Java来做!

JavaConfig是Spring的子项目,在Spring4.0以后,称为一个核心功能。

image-20210510095631316

实体类


@Component
public class User {

    private String name;

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

    public String getName() {
        return name;
    }

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

配置类

// 这个也会Spring容器托管,注册到容器中,因为它本来就是一个@Component
// @Configuration代表这是一个配置类,就类似applicationContext.xml
@Configuration
@ComponentScan("com.hing")
@Import(MyConfig2.class)
public class MyConfig {

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

测试类

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context=new AnnotationConfigApplicationContext(MyConfig.class);
        User user = context.getBean("user",User.class);
        System.out.println(user.getName());
    }
}

代理模式

为什么要学习代理模式?因为这就是SpringAOP的底层

代理模式的分类:静态代理 、动态代理

image-20210510134646993

静态代理

角色分析:

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

代码步骤:

  1. 接口

    public interface Rent {
        public void rent();
    }
    
  2. 真实角色

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

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

    public class Client {
        public static void main(String[] args) {
            //房东要出租房子
            Host host=new Host();
            //代理,中介帮房东租房子,但是代理角色一般会有一些附属操作!
            Proxy proxy=new Proxy(host);
    
            //你不用面对房东直接找中介租房即可
            proxy.rent();
        }
    }
    

代理模式的好处:

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

缺点

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

加深理解

  1. 接口

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

    public class UserServiceImpl implements UserService {
        public void add() {
            System.out.println("新增一个用户");
        }
    
        public void update() {
            System.out.println("修改一个用户");
        }
    
        public void delete() {
            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 update() {
            log("update");
            userService.update();
        }
    
        public void delete() {
            log("delete");
            userService.delete();
        }
    
        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

image-20210510160916784

动态代理

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

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

改造上边的userService静态代理代码实现:

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());
        return method.invoke(target,args);
    }
    public void log(String msg){
        System.out.println("调用了"+msg+"方法!");
    }
}
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();
    }
}

动态代理的好处:

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

AOP

什么是AOP

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

image-20210510162238261

AOP在Spring中的作用

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

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

image-20210510163852331

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

image-20210510163947859

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

使用Spring实现AOP

使用AOP织入,需要导入一个依赖包

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

基础共用类service+测试类

//service类
public interface UserService {
    public void add();
    public void update();
    public void delete();
    public void select();
}
//service实现类
public class UserServiceImpl implements UserService {
    public void add() {
        System.out.println("新增一个用户");
    }

    public void update() {
        System.out.println("修改一个用户");
    }

    public void delete() {
        System.out.println("删除一个用户");
    }

    public void select() {
        System.out.println("查询一个用户");
    }
}
//测试类
public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

        //动态代理代理的是接口
        UserService userService=context.getBean("userService",UserService.class);
        userService.add();
    }
}

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

public class BeforeLog implements MethodBeforeAdvice {
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println(method.getName()+"被执行了");
    }
}

public class AfterLog implements AfterReturningAdvice {

    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println("执行力"+method.getName()+"方法,返回值是"+returnValue);
    }
}
<?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">

    <!--方法一:使用原生的Spring API接口-->
    <!--配置AOP需要导入AOP的约束-->
    <aop:config>
        <!--切入点 expression表达式,execution(要执行的位置!* * * * *)-->
        <aop:pointcut id="pointcut" expression="execution(* com.hing.service.UserServiceImpl.*(..))"/>

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

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

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

    public void after(){
        System.out.println("============执行方法后=============");
    }
}
<!--方法二:使用自定义类方式-->
<bean id="diy" class="com.hing.diy.DiyPointCut"/>
<aop:config>
    <!--自定义切面,ref要引用的类-->
    <aop:aspect ref="diy">
        <!--切入点-->
        <aop:pointcut id="pointcut" expression="execution(* com.hing.service.UserServiceImpl.*(..))"/>
        <!--通知-->
        <aop:before method="before" pointcut-ref="pointcut"/>
        <aop:after method="after" pointcut-ref="pointcut"/>
    </aop:aspect>
</aop:config>

方法三:使用注解实现!

@Aspect //标注这个类是一个切面
public class AnnotationPointCut {

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

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

    @Around("execution(* com.hing.service.UserServiceImpl.*(..))")
    public void aroud(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("环绕前");

        Signature signature = pjp.getSignature();//获得签名

        System.out.println(signature);
        Object proceed = pjp.proceed(); //执行方法

        System.out.println("环绕后");
        System.out.println(proceed);
    }
}
<!--方法三:注解方式-->
<bean id="annotationPointCut" class="com.hing.diy.AnnotationPointCut"/>
<!--开启注解支持! JDK(默认:proxy-target-class="false") cglib(proxy-target-class="true")-->
<aop:aspectj-autoproxy />
posted @ 2021-05-11 15:27  地球小星星  阅读(134)  评论(0)    收藏  举报