before, myAnnotation.value : son
son.hello()
before, myAnnotation.value : son
father.hello2()
父类有注解,子类无注解:
before, myAnnotation.value : father
father.hello()
before, myAnnotation.value : father
father.hello2()
son.hello()
father.hello2()
父类有注解,子类有注解
before, myAnnotation.value : father
father.hello()
before, myAnnotation.value : father
father.hello2()
before, myAnnotation.value : son
son.hello()
before, myAnnotation.value : son
father.hello2()
我们从上面总结出一套规律:
@within
:@Before
通知方法的myAnnotation
参数指的是调用方法所在的类上面的注解,就是这个方法是在哪个类上定义的
@target
:@Before
通知方法的myAnnotation
参数指的是调用方法运行时所属于的类上面的注解
我们最后总结一下,如果父类和子类上都标有注解,@within
和@target
的所得到实际注解的区别
| | @within | @target |
| — | — | — |
| 父类方法 | 父类注解 | 父类注解 |
| 子类不重写方法 | 父类注解 | 子类注解 |
| 子类重写方法 | 子类注解 | 子类注解 |
@target
看起来跟合理一点
从上面的分析可以看出,其实用@target
更符合我们想要的结果,在某个类上面加一个注解,拦截的时候就会获取这个类上面的注解,跟父类完全没有关系了
但这个时候会遇到一个问题,就是不相关的类都会生从代理类,
例子如下:
public class NormalBean {
public void hello() {
}
}
@Configuration
@EnableAspectJAutoProxy(exposeProxy = true)
public class Config {
@Bean
public Father father() {
return new Father();
}
@Bean
public Son son() {
return new Son();
}
@Bean
public 《一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》无偿开源 威信搜索公众号【编程进阶路】 NormalBean normalBean() {
return new NormalBean();
}
}
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class,
MyAspect.class);
Father father = context.getBean(“father”, Father.class);
father.hello();
father.hello2();
Son son = context.getBean(Son.class);
son.hello();
son.hello2();
NormalBean normalBean = context.getBean(NormalBean.class);
System.out.println(normalBean.getClass());
}
}
输出:
class cn.eagleli.sp