扫包+参数的方式实现切面
以前总是使用配置扫包的配置+入参来管理控制切面,类似这样
@Aspect
@Component
public class TestAspect {
@Pointcut("execution(public com.*.api.impl..*(..)) AND args(com.*.TestRequest))")
public void accessControl() {
}
@Around(value = "Pointcut()")
public Object doAround(ProceedingJoinPoint invocation) throws Throwable {
Object[] args = invocation.getArgs();
Object obj = null;
try {
// 前置处理
***
//调用实际业务方法
obj = invocation.proceed(args);
return obj;
} catch (Exception e) {
e.printStackTrace();
return obj;
}
}
}
但这种方式总是不灵活。
- 这代表了被切面管控的类方法,总是只能存在于一个包下,且使用固定的入参
- 这代表了该包下使用这个入参的方法必定需要被切面管控
那又更灵活一点的管控方式吗?
用注解来管理切面
首先自己搞一个自定义的注解
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface TestApi {
}
切面指定管控的类用注解来管理
@Aspect
@Component
public class TestAspect {
@Pointcut(value = "@within(com.***.annotations.TestApi)")
public void mtopPointCut() {
}
@Around(value = "Pointcut()")
public Object doAround(ProceedingJoinPoint invocation) throws Throwable {
Object[] args = invocation.getArgs();
Object obj = null;
try {
// 前置处理
***
//调用实际业务方法
obj = invocation.proceed(args);
return obj;
} catch (Exception e) {
e.printStackTrace();
return obj;
}
}
}
此时需要这个切面管控的类,只需给上这个自定义的注解,调用类下的方法时都会过这个切面
@TestApi
public class TestServiceImpl {
public String operate(Strin[] arg) {
******
}
}