可配置与使用 Spring 和 AspectJ 的组件
使用 AspectJ 时,为什么使用 @Component 而不是 @Configurable。
我已经为 @Transactional 支持、自调用方面以及注入 JPA 实体设置了 Spring 和 AspectJ。 这很好用。
我对大多数需要注入的类使用@Component,因此要么将它们注入到它们的依赖项中。 或者,当我不能时,注入 ApplicationContext 然后使用 getBean() 作为最后的手段。 我仅为需要注入的 JPA 实体(Hibernate)保留 @Configurable。 我还开始使用 @Configurable 进行 jUnit 测试,以使编写测试变得容易。 这也很有效。
但我很好奇。 如果 AspectJ 现在使用 @Configurable 注释自动注入(豆化)任何内容,无论其构造方式如何; getBean()、new()、@Autowired。 为什么我不直接对我的所有 bean 改用 @Configurable 呢? 然后我可以完全取消应用程序上下文和 getBean() ,而只使用 new() 任何我无法注入的类。
我意识到我没有提到 XML bean 配置。 我并不回避这一点,但这个项目恰好不需要任何东西。 我只是在测试时构造函数或设置器注入依赖项。 好简单。
When using AspectJ, why use @Component over @Configurable.
I've got Spring and AspectJ setup for @Transactional support, aspects on self-invocation, and injection into JPA entities. This works great.
I'm using @Component for most classes that need injection, and thus either having them injected into their dependencies. Or, when I can't, injecting the ApplicationContext and then using getBean() as a last resort. And I'm reserving @Configurable for only JPA entities (Hibernate) that need injection. I've also started using @Configurable for jUnit tests, to make writing tests easy. This also works great.
But I'm curious. If AspectJ is now auto-injecting (beanifying) anything with the @Configurable annotation, regardless of how its constructed; getBean(), new(), @Autowired. Why wouldn't I just switch to using @Configurable for all my beans? Then I can do away with the application context and getBean() altogether, and just new() any classes I can't inject.
I realize that I made no mention of XML bean configuration. I don't shy away from that, but this project doesn't happen to require any. I just constructor or setter inject the dependencies when testing. very easy.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
@Component 是一个 Spring 标记接口,它可以在自动检测 bean 时为 Spring 提供线索。
@Configurable 是 AOP 加载时编织的东西使用的标记。
两者其实并没有太多关系。
@Component is a Spring marker interface which can give Spring clues when it comes to auto-detection of beans.
@Configurable is a marker used by the AOP load-time-weaving stuff.
The two don't really have much to do with each other.
@Component
用于将由 Spring 本身实例化的类,而@Configurable
用于将由您自己的代码或另一个框架(Hibernate 的实体)实例化的类例如,Servlet 容器的 Servlet。@Component
is for classes which will be instantiated by Spring itself, while@Configurable
is for classes which will be instantiated by your own code, or by another framework — entities by Hibernate or Servlets by the servlet container, for instance.不应始终使用 @Configurable 的原因之一是它会增加大量开销:应用程序启动通常需要更长的时间,并且创建新实例会变得更慢。
对于@Component,你根本不需要它,因为通常所有实例都是由Spring管理的。
One reason why you should not always use
@Configurable
is that it adds a lot of overhead: it often takes much longer for the app to start, and creating new instances becomes slower.For
@Component
you don't need it at all, because normally all the instances are managed by Spring.