spring aop怎么写

fiy 其他 36

回复

共3条回复 我来回复
  • fiy的头像
    fiy
    Worktile&PingCode市场小伙伴
    评论

    在Spring框架中,使用AOP(面向切面编程)可以实现对程序进行横切面的功能扩展。下面是Spring AOP的基本步骤和示例代码。

    1. 导入相关依赖
      在项目的pom.xml文件中导入Spring AOP的依赖。
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>
    
    1. 编写切面类
      创建一个切面类,该类包含了需要在目标方法执行前后执行的逻辑。
    @Aspect
    @Component
    public class LoggingAspect {
    
        @Before("execution(* com.example.demo.service.UserService.*(..))")
        public void beforeAdvice(JoinPoint joinPoint) {
            System.out.println("Before Advice: Executing " + joinPoint.getSignature().getName());
        }
    
        @AfterReturning(pointcut = "execution(* com.example.demo.service.UserService.*(..))", returning = "result")
        public void afterReturningAdvice(JoinPoint joinPoint, Object result) {
            System.out.println("After Returning Advice: Executing " + joinPoint.getSignature().getName());
            System.out.println("Result: " + result);
        }
    
        @AfterThrowing(pointcut = "execution(* com.example.demo.service.UserService.*(..))", throwing = "ex")
        public void afterThrowingAdvice(JoinPoint joinPoint, Exception ex) {
            System.out.println("After Throwing Advice: Executing " + joinPoint.getSignature().getName());
            System.out.println("Exception: " + ex.getMessage());
        }
    
        @Around("execution(* com.example.demo.service.UserService.*(..))")
        public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
            System.out.println("Around Advice: Before execution of " + joinPoint.getSignature().getName());
            Object result = joinPoint.proceed();
            System.out.println("Around Advice: After execution of " + joinPoint.getSignature().getName());
            return result;
        }
    }
    

    在切面类中,我们使用了几个常用的注解,包括@Before@AfterReturning@AfterThrowing@Around

    • @Before:在目标方法执行前执行。
    • @AfterReturning:在目标方法执行后执行,可以获取目标方法的返回值。
    • @AfterThrowing:在目标方法抛出异常时执行。
    • @Around:可以在目标方法执行前后执行,还可以决定是否执行目标方法。

    注意:切面类需要被Spring容器扫描到,所以需要加上@Component注解。

    1. 配置AOP代理
      在Spring Boot项目中,可以通过在启动类上添加@EnableAspectJAutoProxy注解启用AOP代理。
    @SpringBootApplication
    @EnableAspectJAutoProxy
    public class DemoApplication {
        // ...
    }
    

    以上就是Spring AOP的基本编写步骤和示例代码。实际使用时,可以根据需要编写不同的切面类,并在切面类中定义不同的切点和通知逻辑来实现具体的功能扩展。

    1年前 0条评论
  • worktile的头像
    worktile
    Worktile官方账号
    评论

    Spring AOP(面向切面编程)是Spring框架提供的一种功能强大的编程方式,用于实现横切关注点的分离和重用。下面是使用Spring AOP的一些常见方式和示例:

    1. 配置切面:
      在Spring配置文件中,通过使用aop:aspect元素来定义一个切面,并使用aop:pointcut元素定义一个切入点,然后在切面中添加需要在切入点处执行的通知。例如:
    <beans xmlns:aop="http://www.springframework.org/schema/aop" 
           xsi:schemaLocation="http://www.springframework.org/schema/aop 
           http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">
    
        <aop:aspect ref="myAspect">
            <aop:pointcut id="myPointcut" expression="execution(* com.example.service.*.*(..))"/>
            
            <aop:before method="before" pointcut-ref="myPointcut"/>
            <aop:after method="after" pointcut-ref="myPointcut"/>
        </aop:aspect>
    
        <bean id="myAspect" class="com.example.aspect.MyAspect"/>
        <bean id="myService" class="com.example.service.MyService"/>
    </beans>
    
    1. 定义切面类:
      在切面类中,可以定义多个通知方法,分别在目标方法执行前、执行后、抛出异常时等不同的时机执行。通知方法可以通过使用 @Before、@After、@AfterReturning、@AfterThrowing 注解来标记。例如:
    @Aspect
    @Component
    public class MyAspect {
    
        @Before("execution(* com.example.service.*.*(..))")
        public void before() {
            // 在目标方法执行前执行的代码
        }
    
        @After("execution(* com.example.service.*.*(..))")
        public void after() {
            // 在目标方法执行后执行的代码
        }
    }
    
    1. 使用切点表达式:
      切点表达式用于定义切入点的位置,可以使用不同的通配符和关键字来指定目标方法。例如,execution(* com.example.service..(..)) 表示匹配 com.example.service 包下的所有类的所有方法。常用的通配符有 *(匹配任意字符)和 ..(匹配任意数量的子包)。其他的关键字包括:within、args、@annotation 等。

    2. 使用不同类型的通知:
      Spring AOP支持多种类型的通知,常用的有@Before(在目标方法之前执行)、@After(在目标方法之后执行)、@AfterReturning(在目标方法返回后执行)、@AfterThrowing(在目标方法抛出异常后执行)等。通知方法可以携带不同类型的参数,如 JoinPoint(提供有关连接点的信息)、ProceedingJoinPoint(只用于 @Around 通知,可用于控制目标方法的执行等)。

    3. 使用注解方式配置切面:
      除了XML配置外,Spring AOP还支持使用注解来配置切面。可以将@Aspect注解添加到切面类上,使用其他注解来标记通知,如@Before、@After等。同时,也可以使用@Pointcut注解来定义切入点。例如:

    @Aspect
    @Component
    public class MyAspect {
    
        @Pointcut("execution(* com.example.service.*.*(..))")
        public void myPointcut() {
        }
    
        @Before("myPointcut()")
        public void before() {
            // 在目标方法执行前执行的代码
        }
    
        @After("myPointcut()")
        public void after() {
            // 在目标方法执行后执行的代码 
        }
    }
    

    以上是使用Spring AOP的一些常见方式和示例。使用Spring AOP可以轻松地实现日志记录、事务管理、权限控制等横切关注点的管理。

    1年前 0条评论
  • 不及物动词的头像
    不及物动词
    这个人很懒,什么都没有留下~
    评论

    Spring AOP(Aspect-Oriented Programming)是Spring框架提供的一个面向切面编程的特性。它允许开发人员通过在不修改源代码的情况下,将横切关注点与核心业务逻辑进行分离。在Spring AOP中,开发人员可以使用切面(Aspect)定义横切关注点,并将其与目标对象的方法进行匹配。当目标对象的方法被调用时,切面中定义的逻辑会被织入到目标对象的方法中。

    下面,我将为你详细介绍如何在Spring AOP中编写代码。

    1. 添加依赖
      首先,在你的Spring项目中添加所需的依赖。Spring AOP的相关依赖通常在Spring框架的核心依赖中已经包含了,但你可能还需要添加AspectJ依赖。你可以通过Maven或Gradle等构建工具来添加依赖。

    Maven依赖配置:

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
        </dependency>
    </dependencies>
    
    1. 定义切面
      在Spring AOP中,切面由一个带有@Aspect注解的Java类表示。在切面类中,你可以定义切入点表达式(Pointcut Expression)和增强逻辑(Advice)。
    package com.example.aspect;
    
    import org.aspectj.lang.ProceedingJoinPoint;
    import org.aspectj.lang.annotation.Around;
    import org.aspectj.lang.annotation.Aspect;
    import org.springframework.stereotype.Component;
    
    @Aspect
    @Component
    public class LoggingAspect {
    
        @Around("execution(* com.example.service.*.*(..))")
        public Object logMethodExecution(ProceedingJoinPoint joinPoint) throws Throwable {
            // 执行前逻辑
            System.out.println("Method execution started: " + joinPoint.getSignature());
    
            // 执行目标方法
            Object result = joinPoint.proceed();
    
            // 执行后逻辑
            System.out.println("Method execution completed: " + joinPoint.getSignature());
    
            return result;
        }
    }
    

    在上面的例子中,我们定义了一个切面类LoggingAspect,并使用@Aspect@Component注解进行标记。@Aspect表示这是一个切面类,@Component表示这个类将被Spring框架进行管理。logMethodExecution方法是一个增强逻辑,使用了@Around注解来定义它的切入点表达式。这个切入点表达式匹配了com.example.service包下的所有方法。

    logMethodExecution方法中,我们使用ProceedingJoinPoint对象来执行目标方法,通过joinPoint.getSignature()可以获取到目标方法的签名信息。在方法调用前后,我们加入了打印日志的逻辑。

    1. 启用Spring AOP
      为了使切面生效,你需要在Spring配置文件中启用Spring AOP。

    XML配置:

    <aop:aspectj-autoproxy />
    

    Java配置(使用@EnableAspectJAutoProxy注解):

    @Configuration
    @EnableAspectJAutoProxy
    public class AppConfig {
        // 配置其他Bean
    }
    
    1. 测试切面
      编写一个测试类来验证切面是否正常工作。
    package com.example;
    
    import com.example.service.MyService;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.ConfigurableApplicationContext;
    
    @SpringBootApplication
    public class Application {
    
        public static void main(String[] args) {
            ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
    
            MyService myService = context.getBean(MyService.class);
            myService.doSomething();
        }
    }
    
    package com.example.service;
    
    import org.springframework.stereotype.Service;
    
    @Service
    public class MyService {
    
        public void doSomething() {
            System.out.println("Doing something...");
        }
    }
    

    运行这个测试类,你将看到类似以下的输出:

    Method execution started: void com.example.service.MyService.doSomething()
    Doing something...
    Method execution completed: void com.example.service.MyService.doSomething()
    

    这表示切面已经成功织入到了目标方法中。

    以上就是在Spring AOP中编写切面的基本步骤。你可以根据实际需求,通过定义不同的切面和切入点表达式来实现更加复杂的功能。希望这些信息对你有帮助!

    1年前 0条评论
注册PingCode 在线客服
站长微信
站长微信
电话联系

400-800-1024

工作日9:30-21:00在线

分享本页
返回顶部