问题描述
情景如下,定义一个注解,一个aspectj配置类。
注解只能放在method上,功能就是aop打印注解的字符串。
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface Dsa {
String value();
}
@Slf4j
@Aspect
@Component
public class DsAop {
@Before("@annotation(Dsa)")
public void before(JoinPoint point) {
Class<?> className = point.getTarget().getClass();
String methodName = point.getSignature().getName();
//得到方法的参数的类型
Class[] argClass = ((MethodSignature) point.getSignature()).getParameterTypes();
String dataSource = "default";
try {
// 得到访问的方法对象
Method method = className.getMethod(methodName, argClass);
// 判断是否存在@DS注解
if (method.isAnnotationPresent(Dsa.class)) {
Dsa annotation = method.getAnnotation(Dsa.class);
// 取出注解中的数据源名
dataSource = annotation.value();
}
} catch (Exception e) {
e.printStackTrace();
log.info("aop异常:{}", e.getLocalizedMessage());
}
log.info("db 替换为:{}", dataSource);
}
}
现在在Controller里这样配置
@Controller
public class MyController {
@ResponseBody
@GetMapping
@Dsa("AAAAAAAAAAA")
public String t1() {
return work();
}
public String work() {
return "yes";
}
}
发现是可以正确的走进aop并打印字符串的。
但是假如改成这样配置:
@Controller
public class MyController {
@ResponseBody
@GetMapping
public String t1() {
return work();
}
@Dsa("AAAAAAAAAAA")
public String work() {
return "yes";
}
}
就不能走进aop?
理论上这个aop不是可以拦截所有带有这个注解的method吗?
spring的aop基于代理,默认情况下,只有从外部调用方法才会走切面,内部调用不会