如何使用 AOP 和自定义注解?

本文详细讲解了Spring AOP的概念、术语及如何在SpringBoot项目中实现AOP功能,包括前置、后置、环绕等通知类型,并演示了自定义注解的创建与应用。

640?wx_fmt=gif

640?wx_fmt=jpeg

作者 | 一个程序员的成长

责编 | 胡巍巍

记得今年年初刚开始面试的时候,被问的最多的就是你知道Spring的两大核心嘛?那你说说什么是AOP,什么是IOC?我相信你可能也被问了很多次了。


640?wx_fmt=png

到底是什么是AOP?


所谓AOP也就是面向切面编程,能够让我们在不影响原有业务功能的前提下,横切扩展新的功能。这里面有一个比较显眼的词我们需要注意一下,横切,它是基于横切面对程序进行扩展的。


640?wx_fmt=png

AOP相关术语


在Spring的AOP中有很多的术语,而且容易混淆,大家一定要先搞清楚这几个概念:

  • 连接点(Joinpoint):在程序执行过程中某个特定的点,比如类初始化前、类初始化后,方法调用前,方法调用后;

  • 切点(Pointcut):所谓切点就是你所切取的类中的方法,比如你横切的这个类中有两个方法,那么这两个方法都是连接点,对这两个方法的定位就称之为切点;

  • 增强(Advice):增强是织入到连接点上的一段程序,另外它还拥有连接点的相关信息;

  • 目标对象(Target):增强逻辑的织入目标类,就是我的增强逻辑植入到什么位置;

  • 引介(Introduction):一种特殊的增强,它可以为类添加一些属性喝方法;

  • 织入(Weaving):织入就是讲增强逻辑添加到目标对象的过程;

  • 代理(Proxy):一个类被AOP织入增强后,就会产生一个结果类,他是融合了原类和增强逻辑的代理类;

  • 切面(Aspect):切面由切点和增强组成,他是横切逻辑定义和连接点定义的组成;


640?wx_fmt=png

AOP功能实践


我们这里主要是学习SpringBoot中的一些功能,所以我们这里用的是SpringBoot工程,版本也是最新的2.0.5版本。

创建SpringBoot工程就不说了,我们直接引入Maven的依赖:

<parent>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-parent</artifactId>
       <version>2.0.5.RELEASE</version>
       <relativePath/> <!-- lookup parent from repository -->
   </parent>

   <properties>
       <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
       <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
       <java.version>1.8</java.version>
   </properties>

   <dependencies>
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-web</artifactId>
           <exclusions>
               <exclusion>
                   <groupId>org.springframework.boot</groupId>
                   <artifactId>spring-boot-starter-tomcat</artifactId>
               </exclusion>
           </exclusions>
       </dependency>
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-jetty</artifactId>
       </dependency>

       <!-- 引入AOP -->
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-aop</artifactId>
       </dependency>
   </dependencies>

   <build>
       <plugins>
           <plugin>
               <groupId>org.apache.maven.plugins</groupId>
               <artifactId>maven-compiler-plugin</artifactId>
               <version>3.6.1</version>
               <configuration>
                   <source>1.8</source>
                   <target>1.8</target>
               </configuration>
           </plugin>
           <plugin>
               <groupId>org.apache.maven.plugins</groupId>
               <artifactId>maven-surefire-plugin</artifactId>
               <version>2.20</version>
               <configuration>
                   <skip>true</skip>
               </configuration>
           </plugin>
           <plugin>
               <groupId>org.springframework.boot</groupId>
               <artifactId>spring-boot-maven-plugin</artifactId>
               <executions>
               </executions>
           </plugin>
       </plugins>
   </build>

首先我们来创建一个Controller类:


 

@RestController
public class LoginController {

   @GetMapping(value = "/username")
   public String getLoginUserName(String userName, Integer age) {
       
       return userName + " --- " + age;
   }
}

创建切面:


 

@Aspect
@Component
public class LogAspect {

   /**
    * 功能描述: 拦截对这个包下所有方法的访问
    *
    * @param:[]
    * @return:void
    **/

   @Pointcut("execution(* com.example.springbootaop.controller.*.*(..))")
   public void loginLog() {
   }

   // 前置通知
   @Before("loginLog()")
   public void loginBefore(JoinPoint joinPoint{

       // 我们从请求的上下文中获取request,记录请求的内容
       ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

       HttpServletRequest request = attributes.getRequest();

       System.out.println("请求路径 : " + request.getRequestURL());
       System.out.println("请求方式 : " + request.getMethod());
       System.out.println("方法名 : " + joinPoint.getSignature().getName());
       System.out.println("类路径 : " + joinPoint.getSignature().getDeclaringTypeName());
       System.out.println("参数 : " + Arrays.toString(joinPoint.getArgs()));
   }

   @AfterReturning(returning = "object", pointcut = "loginLog()")
   public void doAfterReturning(Object object{

       System.out.println("方法的返回值 : " + object);
   }

   // 方法发生异常时执行该方法
   @AfterThrowing(throwing = "e",pointcut = "loginLog()")
   public void throwsExecute(JoinPoint joinPoint, Exception e{

       System.err.println("方法执行异常 : " + e.getMessage());
   }

   // 后置通知
   @After("loginLog()")
   public void afterInform() {

       System.out.println("后置通知结束");
   }

   // 环绕通知
   @Around("loginLog()")
   public Object surroundInform(ProceedingJoinPoint proceedingJoinPoint{

       System.out.println("环绕通知开始...");

       try {
           Object o =  proceedingJoinPoint.proceed();
           System.out.println("方法环绕proceed,结果是 :" + o);
           return o;
       } catch (Throwable e) {
           e.printStackTrace();
           return null;
       }
   }
}

注解概述:

  • @Apsect:将当前类标识为一个切面;

  • @Pointcut:定义切点,这里使用的是条件表达式;

  • @Before:前置增强,就是在目标方法执行之前执行;

  • @AfterReturning:后置增强,方法退出时执行;

  • @AfterThrowing:有异常时该方法执行;

  • @After:最终增强,无论什么情况都会执行;

  • @Afround:环绕增强;

测试:

640

异常测试:

640


640?wx_fmt=png

定义自定义注解


应用场景:在我之前上个项目的时候,有这样一个注解,就是在访问其他接口的时候必须要登录,那么这个时候我们就定义一个注解,让它去对用户是否登录进行校验,那么基于这样的一个场景,我们来定义一个校验登录的注解。

创建一个注解:


 

@Target({ElementType.METHODElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Auth {

   String desc() default "验证是否登录";
}

创建一个AOP切面:


 

@Aspect
@Component
public class LoginAspect {

   @Pointcut(value = "@annotation(com.example.springbootaop.annotation.Auth)")
   public void access() {
   }

   @Before("access()")
   public void before() {

       System.out.println("开始验证用户是否登录...");
   }

   @Around("@annotation(auth)")
   public Object around(ProceedingJoinPoint pj, Auth auth) {

       // 获取注解中的值
       System.out.println("注解中的值 : " + auth.desc());
       try {

           // 检验是否登录 true 已经登录  false 未登录
           Boolean flag = false;

           if (flag == true) {
               return "登录成功";
           } else {
               return "未登录";
           }
       } catch (Throwable throwable) {
           return null;
       }
   }
}

测试未登录:

640

测试登录:

640

这样我们就可以简单的实现了一个登录校验的注解。

通过今天的分享你会使用AOP和自定义注解了吗?我把源码的地址放在下面,有兴趣的朋友可以看看。

GitHub地址:

  • https://github.com/liangbintao/SpringBootIntegration.git

作者:一个非科班出身的屌丝男,自学半年多,找到了一份还不错的工作,我希望做一个专注于Java领域与思维认知的公众号,希望可以带领更多的初学者和入门选手,通过自己努力,得到更多的技术上的提升和思维认知上的拓展。

声明:本文为公众号一个程序员的成长投稿,版权归对方所有。

推荐阅读:

640?wx_fmt=gif

640?wx_fmt=gif

### 回答1: 可以使用Spring AOP来通过自定义注解来实现切入点。首先,定义一个自定义注解,并在需要切入的方法上使用注解,然后定义一个切面,并在切面中使用@Before 或 @Around 注解来拦截被标记的方法,最后,在Spring的配置文件中声明所需的切面,此时,所有被标记的方法都会被拦截。 ### 回答2: 使用Spring AOP切入自定义注解有以下几个步骤: 1. 在项目中引入Spring AOP的依赖,一般为spring-aopspring-aspects。 2. 在配置文件中开启Spring AOP的自动代理功能。可以通过在XML配置文件中添加<aop:aspectj-autoproxy />或在Java配置文件中添加@EnableAspectJAutoProxy注解实现。 3. 创建一个切面类,用于定义切入的逻辑。这个类需要使用@Component或者其他Spring注解进行标识,以便Spring能够扫描到。 4. 在切面类的方法中,使用@Before、@After等注解定义切入点具体的切入操作。例如,使用@Before注解定义在某个注解标记的方法执行之前切入的逻辑。 5. 在注解中定义自定义切点。可以使用@Retention@Target等元注解来配置注解的生命周期使用范围。 6. 在目标类或方法上添加自定义注解。例如,在一个Service类的某个方法上添加自定义注解。 7. 运行项目,Spring会根据配置自动代理目标类,当目标类或方法被调用时,切面类中定义的切入逻辑就会自动被执行。 8. 可以通过配置切入的顺序、通知的类型等来进一步细化切入的逻辑。 通过以上步骤,我们可以使用Spring AOP方便地切入自定义注解,实现对目标类或方法的增强、日志记录、权限控制等功能。 ### 回答3: 使用Spring AOP切入自定义注解需要以下几个步骤: 1. 定义一个自定义注解。可以使用Java提供的`@interface`关键字创建一个注解,例如: ```java @Target(ElementType.METHOD) // 定义注解的作用范围为方法 @Retention(RetentionPolicy.RUNTIME) // 注解在运行时可见 public @interface CustomAnnotation { // 自定义注解的属性 } ``` 2. 创建一个切面类来处理注解。可以使用Spring提供的`@Aspect`注解来标记切面类,并在方法上使用`@Before`、`@After`等注解来定义切入点增强逻辑。例如: ```java @Aspect @Component public class CustomAspect { @Before("@annotation(customAnnotation)") // 拦截带有CustomAnnotation注解的方法 public void beforeMethod(CustomAnnotation customAnnotation) { // 在方法执行前执行的逻辑 } } ``` 3. 配置Spring AOP。在Spring配置文件中添加AOP的配置,例如使用`<aop:aspectj-autoproxy>`标签开启自动代理,并指定切面类的包名,让Spring能够自动扫描并应用切面逻辑。 4. 在目标方法上使用自定义注解。在需要切入的方法上标记使用自定义注解,例如: ```java @CustomAnnotation public void doSomething() { // 方法的实际逻辑 } ``` 这样,在调用`doSomething()`方法时,Spring AOP会拦截到带有`@CustomAnnotation`注解的方法,并执行切面逻辑。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值