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?

- 588,226
- 146
- 1,060
- 1,140

- 4,254
- 29
- 35
3 Answers
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.

- 334,321
- 69
- 703
- 674
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:
@Autowired
@FooQualifier
private YourService service;
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.
-
however, this doesn't solve the question. I still would be able to inject bean in any other class. – Tibor Blenessy Oct 20 '11 at 11:03
-
@saberduck true, it doesn't answer your question, but it's a best practice and should be preferred to your approach – Sean Patrick Floyd Oct 20 '11 at 11:47
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.

- 24,730
- 42
- 175
- 330