spring自定义注解AOP实现

本文介绍如何在SpringBoot项目中使用AOP实现方法拦截。通过定义自定义注解`@TestAnnotation`,并在Controller层的方法上应用该注解,结合`@Aspect`切面类中的`@Before`和`@AfterReturning`注解来实现前置和后置通知的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

基于spring boot 的aop pom配置:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

首先定义注解:

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

    public String name() default "";

}

然后在Controller层中定义测试方法:

    /**
     * @comment 修改密码
     * @author HE JIA
     * @date 2017年7月6日 下午1:45:29
     */
    @RequestMapping(value="updatePwd")
    @ResponseBody
    @TestAnnotation(name="张飞")
    public Map<String,Object> updatePwd(String oldPwd,String newPwd){
        return accountService.updatePwd(oldPwd,newPwd,request);
    }

最后定义aop:

@Aspect
@Order(-99)
@Component  
public class TestAspect {

    @Before("@annotation(test)")  //只过滤实现TestAnnotation注解的接口
    public void beforeTest(JoinPoint point, TestAnnotation test) {
        System.out.println("beforeTest:" + test.name());
    }

    @AfterReturning(value="@annotation(test)",returning="result")  //方法返回值用result获取
    public void afterTest(JoinPoint point, TestAnnotation test,Map<String,Object> result)    {

        System.out.println(result.get("state"));

        System.out.println("afterTest:" + test.name());
    }

}

最后打印:
beforeTest:张飞
error
afterTest:张飞

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值