Spring中@within与@target的一些区别

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值