Spring AOP详解

发布时间:2024年01月05日

AOP相关术语

  1. 连接点(joinpoint)

    被拦截到的点,因为Spring只支持方法类型的连接点,所以在Spring中连接点指的就是被拦截到的方法。

  2. 切入点(pointcut)

    切入点是指我们要对哪些连接点进行拦截的定义

  3. 通知(advice)

    所谓通知指的就是指拦截到连接点之后要执行的代码,通知分为前置、后置、异常、最终、环绕通知五类

  4. 切面(aspect)

    是切入点和通知的结合

  5. 引介(introduction)

    是一种特殊的通知,在不修改代码的前提下,引介可以在运行期为类动态地添加一些方法或字段

  6. 目标对象(Target)

    要代理的目标对象(要增强的类)

  7. 织入(weave)

    将增强应用到目标的过程将advice应用到target的过程

  8. 代理(Proxy)

    一个类被AOP织入增强之后,就产生一个代理类

Spring的AOP配置

配置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>com.by</groupId>
    <artifactId>Spring_AOP_Xml</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!-- Spring常用依赖 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.8.RELEASE</version>
        </dependency>
         <!--支持切点表达式 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>5.1.8.RELEASE</version>
        </dependency>
    </dependencies>
</project>

dao数据访问层

/**
 * 持久层实现类
 */
public class UserDaoImpl implements UserDao {

    @Override
    public void addUser(){
        System.out.println("insert into tb_user......");
    }
}

service业务层

/**
 * 业务层实现类
 */
public class UserServiceImpl implements UserService {

    private UserDao userDao;

    public void addUser(){
        userDao.addUser();
    }
}

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
       			   http://www.springframework.org/schema/beans/spring-beans.xsd
       			   http://www.springframework.org/schema/aop
       			   http://www.springframework.org/schema/aop/spring-aop.xsd">
    
    <bean id="userDao" class="com.by.dao.UserDaoImpl"></bean>
    <bean id="userService" class="com.by.service.UserServiceImpl">
        <property name="userDao" ref="userDao"></property>
    </bean>
</beans>

?web表现层

/**
 * 模拟表现层
 */
public class Client {
    public static void main(String[] args) {
        ApplicationContext ac = 
            new ClassPathXmlApplicationContext("applicationContext.xml");
        //使用对象
        UserService userService = ac.getBean("userService",UserService.class);
        System.out.println(userService.getClass());
        userService.addUser();
    }
}

?创建增强类

public class MyLogAdvice {
    //前置通知
    public void before() {
        System.out.println("前置通知");
    }

    //最终通知
    public void after() {
        System.out.println("最终通知通知");
    }
    //后置通知
    public void afterReturning(){
        System.out.println("后置通知");
    }
    public void afterThrowing(){
        System.out.println("异常通知");
    }


    //环绕通知
    public void around(ProceedingJoinPoint joinPoint) {
        try {
            System.out.println("方法执行前的环绕通知");
            joinPoint.proceed();
            System.out.println("方法执行后的环绕通知");
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }
}

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
       			   http://www.springframework.org/schema/beans/spring-beans.xsd
       			   http://www.springframework.org/schema/aop
       			   http://www.springframework.org/schema/aop/spring-aop.xsd">
    <bean id="userDao" class="com.by.dao.UserDaoImpl"></bean>
    <bean id="userService" class="com.by.service.UserServiceImpl">
        <property name="userDao" ref="userDao"></property>
    </bean>
    <!--增强(advice)-->
    <bean id="MyLogAdvice" class="com.by.advice.MyLogAdvice"></bean>

    <aop:config>
        <!--切点(pointcut)-->
<!--        切点表达式-->
<!--        表达式语法:-->
<!--        execution([修饰符] 返回值类型 包名.类名.方法名(参数))-->
        <aop:pointcut id="pointcut" expression="execution(* com.by.service.*.*(..))"/>
        <!--切面(aspect):把增强应用到切点上-->
        <aop:aspect ref="MyLogAdvice">
<!--            <aop:around method="around" pointcut-ref="pointcut"></aop:around>-->
            <aop:before method="before" pointcut-ref="pointcut"></aop:before>
            <aop:after method="after" pointcut-ref="pointcut"></aop:after>
            <aop:after-throwing method="afterThrowing" pointcut-ref="pointcut"></aop:after-throwing>
            <aop:after-returning method="afterReturning" pointcut-ref="pointcut"></aop:after-returning>
        </aop:aspect>
    </aop:config>
</beans>

测试结果

基于注解的AOP配置

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>com.by</groupId>
    <artifactId>Spring_AOP_Annotation</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!-- Spring常用依赖 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>5.1.8.RELEASE</version>
        </dependency>
    </dependencies>
</project>

dao

@Repository
public class UserDaoImpl implements UserDao {

    @Override
    public void addUser(){
        System.out.println("insert into tb_user......");
    }
}

service

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    public void addUser() {
        userDao.addUser();
    }
}

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"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">

<!--    aop扫描-->
    <context:component-scan base-package="com.by"></context:component-scan>
<!--    开启springAOP对注解的支持-->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>

?web表现层

/**
 * 模拟表现层
 */
public class Client {
    public static void main(String[] args) {
        ApplicationContext ac = 
            new ClassPathXmlApplicationContext("applicationContext.xml");
        //使用对象
        UserService userService = ac.getBean("userServiceImpl",UserService.class);
        userService.addUser();
    }
}

常用注解

  • @Aspect:把当前类声明为切面类

  • @Before:前置通知,可以指定切入点表达式

  • @AfterReturning:后置【try】通知,可以指定切入点表达式

  • @AfterThrowing:异常【catch】通知,可以指定切入点表达式

  • @After:最终【finally】通知,可以指定切入点表达式

  • @Around:环绕通知,可以指定切入点表达式

注解方式实现aop

@Component
@Aspect//增强类标志
public class MyLogAdvice {
    //前置通知
    @Before("execution(* com.by.service.*.*(..))")
    public void before() {
        System.out.println("前置通知");
    }

    //最终通知
    @AfterReturning("execution(* com.by.service.*.*(..))")
    public void after() {
        System.out.println("最终通知通知");
    }
    //后置通知
    @After("execution(* com.by.service.*.*(..))")
    public void afterReturning(){
        System.out.println("后置通知");
    }
    @AfterThrowing("execution(* com.by.service.*.*(..))")
    public void afterThrowing(){
        System.out.println("异常通知");
    }


    //环绕通知
    @Around("execution(* com.by.service.*.*(..))")
    public void around(ProceedingJoinPoint joinPoint) {
        try {
            System.out.println("方法执行前的环绕通知");
            joinPoint.proceed();
            System.out.println("方法执行后的环绕通知");
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }
}

测试结果

?

文章来源:https://blog.csdn.net/m0_74007708/article/details/135410951
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。