Spring 自定义注解

spring配置文件增加:

<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.0.xsd">

<aop:aspectj-autoproxy proxy-target-class="true" />

创建自定义注解:

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Inherited
public @interface testAop {

	String param();//注解传递的参数,可不加
}

解析注解:

通过@Aspect注解使该类成为切面类

通过@Pointcut 指定切入点 ,这里指定的切入点为TestAop注解类型,也就是被@TestAop注解修饰的方法,进入该切入点。

  • @Before 前置通知:在某连接点之前执行的通知,但这个通知不能阻止连接点之前的执行流程(除非它抛出一个异常)。
  • @Around 环绕通知:可以实现方法执行前后操作,需要在方法内执行point.proceed(); 并返回结果。
  • @AfterReturning 后置通知:在某连接点正常完成后执行的通知:例如,一个方法没有抛出任何异常,正常返回。
  • @AfterThrowing 异常通知:在方法抛出异常退出时执行的通知。
  • @After 后置通知:在某连接点正常完成后执行的通知:例如,一个方法没有抛出任何异常,正常返回。
@Component
@Aspect
public class TestAopInterceptor {

@Around(value = "execution(public * xxx.xxx.*Controller.*(..)) && @annotation(testAop)")
	public Object proceed(ProceedingJoinPoint pjp, TestAop testAop) throws Throwable {
		Signature signature = pjp.getSignature();
		if (!(signature instanceof MethodSignature)) {
			return pjp.proceed();
		}

		MethodSignature methodSignature = (MethodSignature) signature;
		Method method = methodSignature.getMethod();
		Class<?> clazz = method.getDeclaringClass();
		Annotation annotation = method.getAnnotation(TestAop.class);
		if (annotation == null) {
			return pjp.proceed();
		}

		HttpServletRequest request =
				((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();//获取传递的参数值
		String str = testAop.param();//获取注解的参数值
		

		
		return pjp.proceed();
	}
}

增加注解:

@TestAop(param = "param")//注解,和传参
	public Object test(@RequestBody Map<String, String> requestParam, HttpServletRequest request) {
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值