带有@Component 注释的@Aspect 如何在幕后工作 [英] How @Aspect with @Component annotation works under the hood

查看:37
本文介绍了带有@Component 注释的@Aspect 如何在幕后工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找答案,但到目前为止没有运气,因此我来这里是为了一些智慧之言.

I've been looking for an answer for a while, but no luck so far, thus I'm coming here for some words of wisdom.

我已经使用@Aspect 注释创建了一个方面,因为我需要@Autowire 一些单例依赖项我决定用@Component 注释这个方面类并让Spring 来做魔术.它有效,但是...

I've created an aspect using @Aspect annotation, because I need to @Autowire some singleton dependencies I've decided to annotate this aspect class with @Component and let the Spring to do the magic. It works, however ...

我相当熟悉 AOP 概念、它的编织方式和不同的风格(cglib 与 aspectj),但对我来说它是如何在幕后工作的并不完全直观.

I'm fairly familiar with AOP concept, what's weaving and different flavors of it (cglib vs aspectj) but it's not fully intuitive to me how it works under the hood.

@Component 意味着给定的类在给定的上下文中将是单例,@Aspect 意味着方面类的内容将在运行时/编译期间以某种方式编织到目标类中 - 而这个目标类不是单例而是例如原型.那么我最后会得到什么?

@Component means a given class will be a singleton within a given context, @Aspect means that the content of an aspect class will be somehow weaved into the target class during runtime/compilation - and this target class is not a singleton but prototype for instance. So what I'm ending up with at the end?

推荐答案

Spring AOP 不进行编译时编织,也不修改建议目标的代码.相反,它与围绕连接点编织的代理一起工作.这就是为什么 Spring AOP 方面并被用作(单件)组件、自动装配它们的字段等,就像任何其他 Spring 代理一样.

Spring AOP does not do compile-time-weaving and does not modify the code of the advised target. Instead it works with proxies that are weaved around the joinpoints. That is why Spring AOP aspects and be used as (singleton) components, have their fields autowired, etc., like any other Spring Proxy.

这也是为什么 Spring AOP 方面只适用于公共方法执行,而不适用于字段访问等的原因.

It is also the reason why Spring AOP aspects only work for public method executions, not field accesses and the like.

文档写得非常好,尽可能多地(或尽可能少地)详细介绍:http://docs.spring.io/spring/docs/current/spring-framework-reference/html/aop.html

The documentation is quite well written and goes into as much (or as little) detail as one might like: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/aop.html

这篇关于带有@Component 注释的@Aspect 如何在幕后工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆