springboot Aop 方法拦截、注解拦截

//Action.java
//此注解只能修饰方法
@Target(ElementType.METHOD)
//当前注解如何去保持
@Retention(RetentionPolicy.RUNTIME)
//生成到API文档
@Documented
public @interface Action {
String name();
}

AopConfig.java
//JAVA配置类
@Configuration
//Bean扫描器
@ComponentScan(“com.wangzhi.springboot.aop.test”)
//开启spring对aspectJ的支持
@EnableAspectJAutoProxy
public class AopConfig {}

//这个类下的方法我们采用注解来拦截
@Service
public class DemoAnnotationService {

@Action( name = "注解式拦截的add操作")
public void add() {}

}

//这个类下的方法我们采用方法规则来拦截
@Service
public class DemoMethodService {
public void add() {}
}

//LogAspect.java
@Aspect
@Component
public class LogAspect {

//定义切面
@Pointcut("@annotation(com.wangzhi.springboot.aop.test.Action)")
public void annotationPointCut() {}

//声明一个advice,并使用@pointCut定义的切点
@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());
}
//定义方法拦截的规则
@Before("execution(* com.wangzhi.springboot.aop.test.DemoMethodService.*(..))")
public void before(JoinPoint joinPoint) {
    MethodSignature signature =  (MethodSignature) joinPoint.getSignature();
    //拦截了方法
    Method method = signature.getMethod();
    //直接获取方法名字
    System.out.println("方法规则式拦截" + method.getName());
}

//应该可以
@PointCut(* execution(”com.wangzhi.spring.aop.test.DemoMethodService.*(..)”))
public void executionPointCut();

@Before(“executionPointCut()”)

}

//启动器
public class Application {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AopConfig.class);
DemoMethodService methodService = context.getBean(DemoMethodService.class);
DemoAnnotationService annotationService = context.getBean(DemoAnnotationService.class);

    annotationService.add();
    methodService.add();

    context.close();
}

}

pom.xml依赖


org.springframework
spring-aop
4.3.12.RELEASE

<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjrt -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjrt</artifactId>
    <version>1.8.10</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.8.10</version>
</dependency>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值