0

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?

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
Tibor Blenessy
  • 4,254
  • 29
  • 35

3 Answers3

3

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.

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
1

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.

Community
  • 1
  • 1
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
0

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.

Don Rhummy
  • 24,730
  • 42
  • 175
  • 330