Spring AOP(AspectJ注解式拦截和方法规则式拦截实现)

1、编写拦截规则的注解

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

	String name();

}

2、编写使用注解的被拦截类

@Service
public class DemoAnnotationService {

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

}

3、编写使用方法规则的被拦截类

@Service
public class DemoMethodService {

	public void add(){}

}

4、编写切面

@Aspect
@Component
public class LogAspect {

	@Pointcut("@annotation(com.aop.Action)")
	public void annotationPointCut() {}

	@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.aop.DemoMethodService.*(..))")
	public void before(JoinPoint joinPoint) {
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
		Method method = signature.getMethod();
		System.out.println("方法规则拦截:" + method.getName());
	}

}

5、配置类

@Configuration
@ComponentScan("com.aop")
@EnableAspectJAutoProxy		//开启Spring对AspectJ的支持
public class AspectJConfig {
}

6、测试

public class Main {
	
	public static void main(String[] args){
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AspectJConfig.class);
		// 注解式
		DemoAnnotationService annotationService = context.getBean(DemoAnnotationService.class);
		annotationService.add();
		// 方法规则式
		DemoMethodService methodService = context.getBean(DemoMethodService.class);
		methodService.add();
	}
	
}

测试结果

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值