如何对 @Autowired 实施限制
我们在项目中使用 Spring 和 @Autowired 来自动注入依赖项。我想禁止从特定模块自动装配某些bean,例如,可以在模块B中自动装配来自模块A的bean,但不能在模块C中自动装配bean。Spring可以吗?
We use Spring in a project and @Autowired
for automatically injecting dependencies. I would like to prohibit autowiring of certain beans from specific modules, so for example, it would be possible to autowire beans from module A in module B, but not in module C. Is it possible with Spring?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不幸的是,单个应用程序上下文中的 bean 是扁平的,即它们都是等效的。但是,如果您定义两个应用程序上下文(父级和子级),则子级中的 Bean 可以访问父级中的 Bean,但反之则不然。在子上下文中定义的 Bean 对于父上下文来说是不可见的。
在您的情况下,您将模块 A 和 B 放置在父上下文中,将 C 放置在子上下文中。Unfortunately beans in single application context are flat i.e. they are all equivalent. However if you define two application contexts, parent and child, then beans from child have access to beans from parent but not the other way around. Beans defined in child context are simply invisible to parent.
In your case you place module A and B in parent context and C in child context.解决问题的最佳方法是通过 javax.inject预选赛。用适当的限定符注释你的bean,然后在注入点使用它:
否则很快就会变得一团糟,哪个实现被注入到哪里。
另一种选择是将一个 bean 指定为 @Primary - 对于给定的注入点,它将优先于其他 bean。
The best way to approach the problem is through javax.inject qualifiers. Annotate your beans with the appropriate qualifier and then use it at the injection point:
Otherwise it will soon become a mess which implementation is injected where.
Another option is to designate one bean as
@Primary
- it will be preferred to other beans for a given injection point.是的,这是可能的,但不是“漂亮”。您可以使用 BeanPostProcessor,当您获得一个 bean 时,检查它是否是您的“父”类型之一以及它的所有子 bean 是否都是允许的类型。否则,您可以抛出异常或将这些字段设置为 null。
Yes, it's possible but not "pretty". You could use a
BeanPostProcessor
and when you get a bean, check if it's one of your "parent" types and if all its child beans are of the allowable types. Otherwise you can either throw an exception or set those fields to null.