SpringAOP之within和target的使用和区别
SpringAOP之within和target
1、概述
@within
和@target
是在配置切点的时候使用到的两个修饰符,都是基于注解来配置切点。
比如当前有注解@A
- "@within(com.annotation.other.A1)"该配置就是:如果某个类上标注了注解@A,那么该类中的所有方法就会被匹配为切点,并且该类的子类中没有重写的父类方法也会被匹配为切点;
- "@target(com.annotation.other.A1)"该配置就是:如果某个类上标注了注解@A,那么该类中的所有方法就会被匹配为切点;
2、约定
本文说的子类和父类关系都是类之间的子类和父类。不涉及注解继承,也就是自定义注解中没有标注元注解–@Inherited。
@within
和@target
正确用法是 "@within/@target(注解的全类名)"
,以下简写为 "@within/@target(@A1)"
3、示例
//注解@A1
@Retention(RetentionPolicy.RUNTIME)
@Target( ElementType.TYPE)
public @interface A1 {
}
//注解@A2
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface A2 {
}
三个有继承关系的类:
@A1
public class Human {
public void say(String sentence)
{
System.out.println("Human says:" + sentence);
}
public void run()
{
System.out.println("Human runs." );
}
public void jump()
{
System.out.println("Human jump." );
}
}
@A2
public class Man extends Human{
@Override
public void run()
{
System.out.println("Man runs." );
}
public void testMan(){
System.out.println("Man testMan." );
}
}
public class Boy extends Man{
@Override
public void jump()
{
System.out.println("Boy jump." );
}
public void test(){
System.out.println("Bot test...");
}
}
对应的类图:
4、配置切面
@Aspect
@Component
public class HumanAspect {
@Before("@within(com.annotation.other.A1)")
public void execute1(){
System.out.println("@within --- A1");
}
@Before("@target(com.annotation.other.A1)")
public void execute2(){
System.out.println("@target --- A1");
}
@Before("@within(com.annotation.other.A2)")
public void execute3(){
System.out.println("@within --- A2");
}
@Before("@target(com.annotation.other.A2)")
public void execute4(){
System.out.println("@target --- A2");
}
}
测试类:
public class SpringApplication {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
Human human = context.getBean("human",Human.class);
System.out.println("--------------- This is a Human ---------------");
human.say("hello");
human.jump();
human.run();
System.out.println("--------------- This is a man ---------------");
Man man = context.getBean("man", Man.class);
man.testMan();
man.run();
System.out.println("--------------- This is a boy ---------------");
Boy boy = context.getBean("boy", Boy.class);
boy.jump();
boy.test();
}
}
测试结果:
--------------- This is a Human ---------------
@within --- A1
@target --- A1
Human says:hello
@within --- A1
@target --- A1
Human jump.
@within --- A1
@target --- A1
Human runs.
--------------- This is a man ---------------
@within --- A2
@target --- A2
Man testMan.
@within --- A2
@target --- A2
Man runs.
--------------- This is a boy ---------------
Boy jump.
Bot test...
参考链接:https://blog.csdn.net/qq_36917119/article/details/108123440
从理论中来,到实践中去,最终回归理论