Spring-AOP注解与方法规则实例

简介: 一、前言在实际开发中,我们很多操作需要拦截来解决问题。例如我们老生常谈的日志和方法操作的一些统计。

一、前言

在实际开发中,我们很多操作需要拦截来解决问题。例如我们老生常谈的日志和方法操作的一些统计。我这里做一个aop例子,以供自己和大家实用起来方便。

本文主要有两种方式解决aop:1、实用注解 2、实用方法规则方法

两种方式都是基于java文件的,为什么没有基于xml,因为xml已经out于太繁琐,比较不是全项目的拦截,所以不用xml配置。

项目链接地址:点击打开链接   https://github.com/yangchangyong0/springaopTest

二、使用注解实现aop

2.1 首先编写注解类

package com.ycy.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Created by ycy on 16/4/8.
 * 编写拦截的注解
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Action {
    String name();
}

2.2 对需要拦截方法加注解

package com.ycy.annotation;

import org.springframework.stereotype.Service;

/**
 * Created by ycy on 16/4/8.\
 * 对需要注解的方法加上注解
 */
@Service
public class DemoAnnotationService {
    @Action(name = "注解连接add方法操作")
    public void add(){
        System.out.println("DemoAnnotationService执行add方法");
    }
}

三、使用方法规则实现aop


3.1 直接编写类(不需要任何其他操作)

package com.ycy.method;

import org.springframework.stereotype.Service;

/**
 * Created by ycy on 16/4/8.
 * 直接编写类,不需要其他任何操作
 */
@Service
public class DemoMethodService {
    public void add(){
        System.out.println("DemoMethodService执行add方法");
    }
}

四、aop切面编写

在切面中,我们使用after 与before ,将两种拦截切面都做了拦截。

package com.ycy.aop;

import com.ycy.annotation.Action;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
//
/**
 * Created by ycy on 16/4/8.
 */
@Aspect//1
@Component//2
public class LogAspect {
    /*拦截累切点编写*/
    @Pointcut("@annotation(com.ycy.annotation.Action)")//3
    public  void annotationPointCut(){
        System.out.println("开始拦截--但是不打印");
    }
    /*使用注解方法拦截*/
    @After("annotationPointCut()")
    public void after(JoinPoint joinPoint){
        MethodSignature signature=(MethodSignature)joinPoint.getSignature();
        Method method=signature.getMethod();
        Action action=method.getAnnotation(Action.class);
        System.out.println("注解拦截方式:"+action.name());//5
    }

    /*使用方法规则拦截*/
    @Before("execution(* com.ycy.method.DemoMethodService.*(..))")//6
    public void before(JoinPoint joinPoint){
        MethodSignature signature=(MethodSignature)joinPoint.getSignature();
        Method method=signature.getMethod();
        System.out.println("方法规则拦截方式:"+method.getName());
    }
}


在使用spring框架配置AOP的时候,不管是通过XML配置文件还是注解的方式都需要定义pointcut"切入点"
例如定义切入点表达式 execution(* com.sample.service.impl..*.*(..))
execution()是最常用的切点函数,其语法如下所示:
 整个表达式可以分为五个部分:
 1、execution(): 表达式主体。
 2、第一个*号:表示返回类型,*号表示所有的类型。
 3、包名:表示需要拦截的包名,后面的两个句点表示当前包和当前包的所有子包,com.sample.service.impl包、子孙包下所有类的方法。
 4、第二个*号:表示类名,*号表示所有的类。
 5、*(..):最后这个星号表示方法名,*号表示所有的方法,后面括弧里面表示方法的参数,两个句点表示任何参数。



五、测试代码

package com.ycy.main;

import com.ycy.annotation.DemoAnnotationService;
import com.ycy.method.DemoMethodService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

/**
 * Created by ycy on 16/4/8.
 * 1使用扫描注解方法建立context
 * 然后执行我们的两个测试方法
 */
@Configuration
@ComponentScan("com.ycy")
@EnableAspectJAutoProxy//1
public class AopconfigTest {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AopconfigTest.class);
        DemoAnnotationService demoAnnotationService = context.getBean(DemoAnnotationService.class);

        DemoMethodService demoMethodService = context.getBean(DemoMethodService.class);

        demoAnnotationService.add();

        demoMethodService.add();
    }
}

测试结果输出
DemoAnnotationService执行add方法
注解拦截方式:注解连接add方法操作
方法规则拦截方式:add
DemoMethodService执行add方法

Process finished with exit code 0





目录
相关文章
|
4月前
|
缓存 监控 Java
SpringBoot @Scheduled 注解详解
使用`@Scheduled`注解实现方法周期性执行,支持固定间隔、延迟或Cron表达式触发,基于Spring Task,适用于日志清理、数据同步等定时任务场景。需启用`@EnableScheduling`,注意线程阻塞与分布式重复问题,推荐结合`@Async`异步处理,提升任务调度效率。
803 128
|
3月前
|
XML Java 数据格式
《深入理解Spring》:AOP面向切面编程深度解析
Spring AOP通过代理模式实现面向切面编程,将日志、事务等横切关注点与业务逻辑分离。支持注解、XML和编程式配置,提供五种通知类型及丰富切点表达式,助力构建高内聚、低耦合的可维护系统。
|
3月前
|
XML Java 应用服务中间件
【SpringBoot(一)】Spring的认知、容器功能讲解与自动装配原理的入门,带你熟悉Springboot中基本的注解使用
SpringBoot专栏开篇第一章,讲述认识SpringBoot、Bean容器功能的讲解、自动装配原理的入门,还有其他常用的Springboot注解!如果想要了解SpringBoot,那么就进来看看吧!
511 2
|
4月前
|
Java 测试技术 数据库
使用Spring的@Retryable注解进行自动重试
在现代软件开发中,容错性和弹性至关重要。Spring框架提供的`@Retryable`注解为处理瞬时故障提供了一种声明式、可配置的重试机制,使开发者能够以简洁的方式增强应用的自我恢复能力。本文深入解析了`@Retryable`的使用方法及其参数配置,并结合`@Recover`实现失败回退策略,帮助构建更健壮、可靠的应用程序。
621 1
使用Spring的@Retryable注解进行自动重试
|
4月前
|
XML Java 数据格式
常用SpringBoot注解汇总与用法说明
这些注解的使用和组合是Spring Boot快速开发和微服务实现的基础,通过它们,可以有效地指导Spring容器进行类发现、自动装配、配置、代理和管理等核心功能。开发者应当根据项目实际需求,运用这些注解来优化代码结构和服务逻辑。
390 12
|
4月前
|
传感器 Java 数据库
探索Spring Boot的@Conditional注解的上下文配置
Spring Boot 的 `@Conditional` 注解可根据不同条件动态控制 Bean 的加载,提升应用的灵活性与可配置性。本文深入解析其用法与优势,并结合实例展示如何通过自定义条件类实现环境适配的智能配置。
248 0
探索Spring Boot的@Conditional注解的上下文配置
|
4月前
|
智能设计 Java 测试技术
Spring中最大化@Lazy注解,实现资源高效利用
本文深入探讨了 Spring 框架中的 `@Lazy` 注解,介绍了其在资源管理和性能优化中的作用。通过延迟初始化 Bean,`@Lazy` 可显著提升应用启动速度,合理利用系统资源,并增强对 Bean 生命周期的控制。文章还分析了 `@Lazy` 的工作机制、使用场景、最佳实践以及常见陷阱与解决方案,帮助开发者更高效地构建可扩展、高性能的 Spring 应用程序。
202 0
Spring中最大化@Lazy注解,实现资源高效利用
|
4月前
|
Java 测试技术 编译器
@GrpcService使用注解在 Spring Boot 中开始使用 gRPC
本文介绍了如何在Spring Boot应用中集成gRPC框架,使用`@GrpcService`注解实现高效、可扩展的服务间通信。内容涵盖gRPC与Protocol Buffers的原理、环境配置、服务定义与实现、测试方法等,帮助开发者快速构建高性能的微服务系统。
978 0
|
6月前
|
Java Spring 容器
SpringBoot自动配置的原理是什么?
Spring Boot自动配置核心在于@EnableAutoConfiguration注解,它通过@Import导入配置选择器,加载META-INF/spring.factories中定义的自动配置类。这些类根据@Conditional系列注解判断是否生效。但Spring Boot 3.0后已弃用spring.factories,改用新格式的.imports文件进行配置。
1106 0
|
7月前
|
人工智能 Java 测试技术
Spring Boot 集成 JUnit 单元测试
本文介绍了在Spring Boot中使用JUnit 5进行单元测试的常用方法与技巧,包括添加依赖、编写测试类、使用@SpringBootTest参数、自动装配测试模块(如JSON、MVC、WebFlux、JDBC等),以及@MockBean和@SpyBean的应用。内容实用,适合Java开发者参考学习。
857 0