首页 > 其他分享 >Spring AOP的几种实现方式

Spring AOP的几种实现方式

时间:2024-07-10 10:55:52浏览次数:9  
标签:Spring void Object System 几种 AOP println public out

1.通过注解实现

1.1导入依赖

<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>5.1.6.RELEASE</version>
        </dependency>

1.2定义注解

import java.lang.annotation.*;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TestAnnotation{
}

1.2定义切面类

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

/*
* 切面类
**/
@Aspect
@Component
public class AnnotationAspect {

    // 定义一个切点:所有被RequestMapping注解修饰的方法会织入advice
    @Pointcut("@annotation(TestAnnotation)")
    private void advicePointcut() {}

    /*
    * 前置通知
    **/
    @Before("advicePointcut()")
    public void before() {
        System.out.println("annotation前置通知");
    }

    @After("advicePointcut()")
    public void after() {
        System.out.println("annotation后置通知");
    }

    @AfterReturning(pointcut = "advicePointcut()")
    public void afterReturning() {
        System.out.println("annotation后置返回通知");
    }

    @AfterThrowing(pointcut = "advicePointcut()", throwing = "ex")
    public void afterThrowing(Exception ex) throws Exception {
        System.out.println("annotation异常通知");
        System.out.println(ex.getMessage());
    }

    @Around("advicePointcut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        Object proceed = null;
        if (!"".equals("admin")) {
            System.out.println("annotation环绕前置");
            proceed = pjp.proceed(pjp.getArgs());
            System.out.println("annotation环绕后置");
        }
        return proceed;
    }
}

2.jdk代理注解方式

2.1.定义接口


public interface TargetInteface {
    void method1();
    void method2();
    int method3(Integer i);
}

2.2.实现接口

public class Target implements TargetInteface{

    /*
    * 需要增强的方法,连接点JoinPoint
    **/
    public void method1() {
        System.out.println("method1 running ...");
    }

    public void method2() {
        System.out.println("method2 running ...");
    }

    public int method3(Integer i) {
        System.out.println("method3 running ...");
        return i;
    }
}

2.3.定义通知

public class TargetAdvice implements MethodInterceptor, MethodBeforeAdvice, AfterReturningAdvice {

    /*
    * 通知/增强
    **/
    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        System.out.println("前置环绕通知");
        Object proceed = methodInvocation.proceed();
        System.out.println("后置环绕通知");
        return proceed;
    }

    @Override
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println("后置返回通知");
    }

    @Override
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println("前置通知");
    }
}

2.4.书写配置文件

<?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 http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <bean id="target" class="com.heaboy.aopdemo.aop.Target"/>

    <bean id="targetAdvice" class="com.heaboy.aopdemo.aop.TargetAdvice"/>

    <bean id="targetProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
        <property name="target" ref="target"/> <!--被代理的类-->
        <property name="interceptorNames" value="targetAdvice"/>  <!--如果用多种增强方式,value的值使用逗号(,)分割-->
        <property name="proxyTargetClass" value="false"/>
        <property name="interfaces" value="com.heaboy.aopdemo.aop.TargetInteface"/>  <!--target实现的接口-->
    </bean>
</beans>

2.5启动测试

public class AopTest {
    public static void main(String[] args) {
        ApplicationContext appCtx = new ClassPathXmlApplicationContext("spring-aop.xml");
        TargetInteface targetProxy = (TargetInteface) appCtx.getBean("targetProxy");
        targetProxy.method1();
        print(targetProxy);
    }
}

3.cglib配置文件方式

3.1.定义被代理的类

public class Target {

    public void method1() {
        System.out.println("method1 running ...");
    }

    public void method2() {
        System.out.println("method2 running ...");
    }

    /*
    * 连接点JoinPoint
    **/
    public int method3(Integer i) {
        System.out.println("method3 running ...");
        int i1 = 1 / i;
        return i;
    }
}

3.2.定义Aspect

import org.aspectj.lang.ProceedingJoinPoint;
/*
* 切面类
**/
public class TargetAspect {

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

    public void after() {
        System.out.println("conf后置通知");
    }

    public void afterReturning() {
        System.out.println("conf后置返回通知");
    }

    public void afterThrowing(Exception ex) throws Exception {
//        System.out.println("conf异常通知");
//        System.out.println(ex.getMessage());
    }

    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        Object proceed = null;
        if (!"".equals("admin")) {
            System.out.println("conf环绕前置");
            proceed = pjp.proceed(pjp.getArgs());
            System.out.println("conf环绕后置");
        }
        return proceed;
    }
}

3.3书写配置文件

<?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/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

    <bean id="target" class="com.heaboy.aopdemo.confaop.Target"/>

    <bean id="targetAspect" class="com.heaboy.aopdemo.confaop.TargetAspect"/>

    <!--proxy-target-class="true" 表示使用cglib代理.默认为false,创建有接口的jdk代理-->
    <aop:config proxy-target-class="true">
        <!--切面:由切入点和通知组成-->
        <aop:aspect ref="targetAspect">
            <!--切入点 pointcut-->
            <aop:pointcut id="pointcut" expression="execution(* com.heaboy.aopdemo.confaop.*.*(..))"/>
            <!--增强/通知 advice-->
            <aop:before method="before" pointcut-ref="pointcut"/>
            <aop:after method="after" pointcut-ref="pointcut"/>
            <aop:around method="around" pointcut-ref="pointcut"/>
            <aop:after-returning method="afterReturning" pointcut-ref="pointcut"/>
            <aop:after-throwing method="afterThrowing" throwing="ex" pointcut-ref="pointcut"/>
        </aop:aspect>
    </aop:config>
</beans>

3.4启动测试

public class AopTest {
    public static void main(String[] args) {
        ApplicationContext appCtx = new ClassPathXmlApplicationContext("spring-confaop.xml");
        Target targetProxy = (Target) appCtx.getBean("target");
        System.out.println(targetProxy.method3(1));
    }
}

标签:Spring,void,Object,System,几种,AOP,println,public,out
From: https://blog.csdn.net/weixin_69039908/article/details/140317018

相关文章

  • spring boot microservices
    微服务包括这些组件,服务注册,服务发现,负载均衡,配置管理,路由,断流器-过流熔断,分布式系统的日记追踪,服务安全等。thecomponentofspringbootmicroservices.springboot,itprovidesthefoudationforbuildingmicroservices.Itsimplifiestheconfigurationanssetup......
  • 毕业设计-基于Springboot+Vue的家政服务管理平台的设计与实现(源码+LW+包运行)
    源码获取:https://download.csdn.net/download/u011832806/89456882基于SpringBoot+Vue的家政服务管理平台开发语言:Java数据库:MySQL技术:SpringBoot+MyBatis+Vue.js工具:IDEA/Ecilpse、Navicat、Maven系统演示视频:链接:https://pan.baidu.com/s/1gssA8jncDvvFfo8NSHDh8g?pw......
  • 毕业设计-基于Springboot+Vue的社区医院管理服务系统的设计与实现(源码+LW+包运行)
    源码获取:https://download.csdn.net/download/u011832806/89456872基于SpringBoot+Vue的社区医院管理服务系统开发语言:Java数据库:MySQL技术:SpringBoot+MyBatis+Vue.js工具:IDEA/Ecilpse、Navicat、Maven系统演示视频:链接:https://pan.baidu.com/s/14Zrh0wu8QdSeEJof1uyc0......
  • SpringBoot 整合 MyBatisPlus框架入门
    步骤1:创建maven工程创建一个空Maven工程,如下:步骤2:pom.xml文件中添加MyBatisPlus相关依赖<dependencies><!--mybatispulus依赖--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter&l......
  • Jenkins集成部署SpringBoot
    Jenkins集成部署SpringBoot1.前言随着业务的增长,需求也开始增多,每个需求的大小,开发周期,发布时间都不一致。基于微服务的系统架构,功能的叠加,对应的服务的数量也在增加,大小功能的快速迭代,更加要求部署的快速化,智能化。因此,传统的人工部署已经心有余而力不足。持续集成,持续部署,持......
  • IDEA社区版搭建Spring工程(03-Spring MVC搭建)
    新建一个基于Maven的"webapp"模板的基础工程在main文件夹下新建java源码文件夹将自动生成的index.jsp移入webapp的view文件夹下,在java下新建一个controller文件夹添加SpringMVC框架所需的POM配置<properties><project.build.sourceEncoding>UTF-8</pro......
  • 利用SpringBoot+rabbitmq 实现邮件异步发送,保证100%投递成功
    在之前的文章中,我们详细介绍了SpringBoot整合mail实现各类邮件的自动推送服务。但是这类服务通常不稳定,当出现网络异常的时候,会导致邮件推送失败。本篇文章将介绍另一种高可靠的服务架构,实现邮件100%被投递成功。类似的短信自动发送等服务也大体相同。一、先来一张流程图......
  • 基于java+springboot+vue实现的音乐网站(文末源码+Lw)102
     功能介绍:本音乐网站管理员功能有个人中心,用户管理,歌曲分类管理,歌曲信息管理,管理员管理,系统管理等。用户可以注册登录,试听歌曲,可以下载歌曲。因而具有一定的实用性。本站是一个B/S模式系统,采用SpringBoot框架,MYSQL数据库设计开发,充分保证系统的稳定性。系统具有界面清晰、......
  • 基于java+springboot+vue实现的校园社团管理平台(文末源码+Lw)101
     本校园社团信息管理系统功能有个人中心,学生管理,社长管理,社团分类管理,社团信息管理,加入社团管理,社团成员管理,社团活动管理,活动报名管理,系统管理等。社长添加社团,管理员审核社团,学生加入社团,社长审核社团。因而具有一定的实用性。本站是一个B/S模式系统,采用SpringBoot框架,MY......
  • 基于springboot+vue实现的大型商场应急预案管理系统(文末源码+Lw)099
    本大型商场应急预案管理系统管理员功能有个人中心,员工管理,预案信息管理,预案类型管理,事件类型管理,预案类型统计管理,事件类型统计管理,应急预案管理。员工可以查看各种预案信息。因而具有一定的实用性。本站是一个B/S模式系统,采用SpringBoot框架,MYSQL数据库设计开发,充分保证系......