3.SpringAOP

什么是AOP?

AOP(Aspect Oriented Programming )即面向切面编程,它与OOP面向对象编程相辅相成,在OOP中,以类作为基本单元,AOP则以切面作为最基本的单元。主要为了降低代码耦合。

OOP的封装写法示例:

组合
组合
组合
Notice
before()
after()
Wolf
Notice.before()
eat()
Notice.after()
Tiger
Notice.before()
eat()
Notice.after()
Other
...

通过上图发现,如果代码中有1000种动物类使用了Notice.before的方法,想把Notice.before替换成eatbefore方法,就需要修改1000处代码。明显不利于开发者进行维护,而使用AOP上述的关系图就变成了下图

组合
组合
继承
继承
继承
Notice
before()
after()
AnimalProxy
+Animal animal
AnimalProxy(Animal animal)
Notice.before()
animal.eat()
Notice.after()
«interface»
Animal
eat()
Wolf
eat()
Tiger
eat()
Other
...

观察上图,我们发现狼和老虎都是动物,那么就让它们共同实现一个Animal接口,使其可以实现Animal animal = new Worf()的多态用法,再通过调用AnimalProxy animalProxy = new AnimalProxy(animal)的方式去调用eat就实现了代理效果。

AOP的简单实现

上述效果不直观我们来看一下简单代码
目录结构如下
在这里插入图片描述

  1. Animal.java
public interface Animal {
    void eat();
}
  1. Notify.java
public class Notice {
    public void before(){
        System.out.println("前置通知:动物们要捕猎了!!!");
    }
    public void after(){
        System.out.println("后置通知:动物们吃完了...");
    }
}
  1. Tiger.java
public class Tiger implements Animal {
    @Override
    public void eat() {
        System.out.println("老虎吃肉");
    }
}

  1. Wolf.java
public class Wolf implements Animal{
    @Override
    public void eat() {
        System.out.println("狼也吃肉");
    }
}

  1. AnimalProxy.java
public class AnimalProxy {
    private Animal animal;
    public AnimalProxy(Animal animal){
        this.animal = animal;
    }
    public void eat(){
        Notice notice = new Notice();
        notice.before();
        animal.eat();
        notice.after();
    }
}
  1. MainTest.java
public class MainTest {
    public static void main(String[] args) {
        Tiger tiger = new Tiger();
        Wolf wolf = new Wolf();
        AnimalProxy tigerProxy = new AnimalProxy(tiger);
        tigerProxy.eat();
        AnimalProxy wolfProxy = new AnimalProxy(tiger);
        wolfProxy.eat();
    }
}

运行结果如下:

前置通知:动物们要捕猎了!!!
老虎吃肉
后置通知:动物们吃完了...
前置通知:动物们要捕猎了!!!
老虎吃肉
后置通知:动物们吃完了...

上述代码只是AOP思想的一个很简单的实现,在实际开发过程中,我们并不需要手写代理代码。但如果需要手写代理的话,可以使用JDK动态代理、CGLIB动态代理。后续如果有时间的话我也会增加相关教程

AOP专业名词

了解aop的专业名词可以让我们更加容易读懂代码

横切关注点

从每个方法上抽出来的非核心代码,可以理解为上述的before()和after()所做的事情(不是方法本身)都是横切关注点

代理(Proxy)

就是代替其它类执行的对象,比如上方的AnimalProxy对象

目标(Target)

被代理的目标对象,比如上方代码的Animal对象

通知(Advice)

每一个横切关注点上做要做的事情都需要使用一个方法来实现,这样的方法就叫通知方法
通知分为以下5种

  • 前置通知:在被代理的目标方法前执行
  • 后置返回通知:在被代理的目标方法成功结束后执行
  • 后置通知:在被代理的方法最终结束后执行
  • 异常通知:在被代理的方法异常结束后执行
  • 环绕通知:使用try…catch…finally结构的围绕被代理目标方法,包含上述的4种位置

连接点(JoinPoint)

程序运行中的任意位置,在aop中可以理解为方法的执行

切入点(Pointcut)

是指需要处理的连接点

如何实现SpringAOP?

实现springAOP有基于xml配置基于注解两种方式

基于xml配置开发(maven)

  1. 配置maven的配置文件pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>spring_aop_xml_01</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
    </properties>
    <dependencies>
<!--运行spring所需的依赖        -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.22</version>
        </dependency>
<!--使用切入点PointJoin类所需的依赖 -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.7</version>
        </dependency>
<!--        使用@Test注解所需要的依赖-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>
  1. 创建切面类MyAspect.java,具体放哪个目录看代码包名
package com.sfh.aspect;


import org.aspectj.lang.JoinPoint;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 切面类
 */
public class MyAspect {
    /**
     * 前置通知模拟
     * @param joinPoint 连接点信息
     */
    public void before(JoinPoint joinPoint){
        Map<String,Object> map = new HashMap<>();
        map.put("方法名:",joinPoint.getSignature().getName());
        map.put("形参列表:",Arrays.toString(joinPoint.getArgs()));
        System.out.println("前置通知模拟:"+map);
    }

    /**
     * 后置通知模拟
     * @param joinPoint 切入点
     */
    public void after(JoinPoint joinPoint){
        Map<String,Object> map = new HashMap<>();
        map.put("方法名:",joinPoint.getSignature().getName());
        map.put("形参列表:", Arrays.toString(joinPoint.getArgs()));
        System.out.println("后置通知模拟:"+map);
    }
}

  1. TestDao.java
package com.sfh.dao;

public interface TestDao {
    void save();
    void modify();
    void delete(int a,int b);
}

  1. TestDaoImpl.java
package com.sfh.dao.impl;

import com.sfh.dao.TestDao;

public class TestDaoImpl implements TestDao {
    public TestDaoImpl() {
        System.out.println("TestDaoImpl构造器");
    }

    @Override
    public void save() {
        System.out.println("保存");
    }

    @Override
    public void modify() {
        System.out.println("修改");
    }

    @Override
    public void delete(int a, int b) {
        System.out.println("删除:"+a+"和"+b);
    }
}

  1. MainTest.java
package com.sfh.test;

import com.sfh.dao.TestDao;
import com.sfh.dao.impl.TestDaoImpl;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainTest {
    @Test
    public void testAspect(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        TestDao bean = context.getBean(TestDao.class);
        bean.delete(4,3);
    }
}


  1. applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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="testDao" class="com.sfh.dao.impl.TestDaoImpl"/>
<!--	定义切面-->
	<bean id="myAspect" class="com.sfh.aspect.MyAspect"/>
<!--	AOP配置-->
	<aop:config>
<!--		切面配置-->
		<aop:aspect ref="myAspect">
<!--			切入点配置-->
			<aop:pointcut id="myPointCut" expression="execution(* com.sfh.dao.*.*.*(..))"/>
<!--			配置前置通知-->
			<aop:before method="before" pointcut-ref="myPointCut" />
<!--			配置后置通知-->
			<aop:after method="after" pointcut-ref="myPointCut" />
		</aop:aspect>
	</aop:config>
</beans>

基于注解开发(Maven)

关于execution(* com.shifuhao.dao.impl.*.*(..)),
看一个完整的例子
execution(public void com.shifuhao.dao.impl.DaoTestImpl.save(..))

executionpublic voidcom.shifuhao.dao.implDaoTestImplsave(..)
固定写法*表示任意权限修饰符和返回值*表示任意包
*..表示任意层级的包
*表示任意类
*abc表示匹配以abc结尾的类或接口
*表示任意方法
get*表示匹配以get开始的方法
..表示任意类型的形参
  1. pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>spring_aop_annotation_01</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.22</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>5.3.22</version>
        </dependency>
    </dependencies>
</project>
  1. myAspect.java
package com.shifuhao.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class MyAspect {
    @Pointcut("execution(* com.shifuhao.dao.impl.*.*(..))")
    private void pointcut(){}
    @Before("pointcut()")
    public void beforeMethod(JoinPoint jp){
        System.out.println("前置通知,方法名:"+jp.getSignature().getName());
    }
    @After("pointcut()")
    public void afterMethod(JoinPoint jp){
        System.out.println("后置通知:方法名:"+jp.getSignature().getName());
    }
    @AfterReturning(value="pointcut()",returning = "r")
    public void afterReturningMethod(JoinPoint jp,Object r){
        System.out.println("后置返回通知,返回结果:"+toString());
    }
    @AfterThrowing(value = "pointcut()",throwing = "e")
    public void afterThrowingMethod(JoinPoint jp,Throwable e){
        System.out.println("异常通知,返回结果:"+e.getMessage());
    }
    @Around("pointcut()")
    public Object Around(ProceedingJoinPoint pjp){
        Object proceed = null;
        try {
            System.out.println("环绕--->前置环绕通知");
             proceed = pjp.proceed();
            System.out.println("环绕--->后置返回通知");
        }catch (Throwable e){
            System.out.println("环绕--->异常通知,"+e.getMessage());
        }finally {
            System.out.println("环绕--->后置通知");
        }

        return proceed;
    }
}

  1. DaoTest.java
package com.shifuhao.dao;

public interface DaoTest {
    void save();
    void modify();
    void delete();
}

  1. DaoTestImpl.java
package com.shifuhao.dao.impl;

import com.shifuhao.dao.DaoTest;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

@Repository("testDao")
public class DaoTestImpl implements DaoTest {
    @Override
    public void save() {
        System.out.println("保存");
    }

    @Override
    public void modify() {
        System.out.println("修改");
    }

    @Override
    public void delete() {
        System.out.println("删除");
    }
}

  1. MainTest.java
package com.shifuhao.test;

import com.shifuhao.dao.DaoTest;


import org.springframework.context.support.ClassPathXmlApplicationContext;


public class MainTest {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        DaoTest bean = (DaoTest) context.getBean("testDao");
        bean.save();
    }
}

  1. applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	   xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop"
	   xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">
	<context:component-scan base-package="com.shifuhao.aspect" />
	<context:component-scan base-package="com.shifuhao.dao" />
	<aop:aspectj-autoproxy />
</beans>

上述代码就是AOP的简单是实现
执行结果为

环绕--->前置环绕通知
前置通知,方法名:save
保存
后置返回通知,返回结果:com.shifuhao.aspect.MyAspect@2dc9b0f5
后置通知:方法名:save
环绕--->后置返回通知
环绕--->后置通知
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值