Spring Boot 中实现代理

功能:定义一个功能,使指定的方法执行前后输出日志信息。

1、定义一个注解,添加的方法上具有该功能,或者添加到类上,类下的所有方法都具有该功能

@Target( {ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface LogAround {

}

2、实现PointCut接口,找出标注注解的方法或类

// 这里是直接继承了一个便捷基类,实现 matches 方法
public class LogAroundPointcut extends StaticMethodMatcherPointcut {

	@Override
	public boolean matches(Method method, Class<?> targetClass) {
		return AnnotatedElementUtils.hasAnnotation(targetClass, LogAround.class) ||
				AnnotatedElementUtils.hasAnnotation(method, LogAround.class);
	}

}

3、实现 Advice,定义增强行为

// 这里继承了 MethodInterceptor,方法拦截。前后打印日志
public class LogAroundInterceptor implements MethodInterceptor {

	@Nullable
	@Override
	public Object invoke(@Nonnull MethodInvocation invocation) throws Throwable {
		System.out.println("before method invoke log....");
		Method method = invocation.getMethod();
		Object[] args = invocation.getArguments();
		Object target = invocation.getThis();
		Object invoke = method.invoke(target, args);
		System.out.println("after method invoke log....");
		return invoke;
	}
}

4、定义一个 Advisor ,把这两个组合起来,并添加到 Spring 中

@Component
public class LogAroundPointcutAdvisor extends AbstractPointcutAdvisor {


	@Override
	public Pointcut getPointcut() {
		return new LogAroundPointcut();
	}

	@Override
	public Advice getAdvice() {
		return new LogAroundInterceptor();
	}

	@Override
	public boolean isPerInstance() {
		return false;
	}

	
}

5、测试bean

@Component
public class AopDemo {

	@LogAround
	public static int sum(int i1, int i2) {
		return i1 + i2;
	}

}

6、测试结果
前后有打印日志,代理成功
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值