Define default implementation for injection in Spring?
Asked Answered
A

1

5

I have a base class that is extended by some other classes. Therefore I have to provide qualifiers for being able to inject a specific instance.

I wonder if I could mark any of these classes (eg the most upper class) as default class, which would be picked up if no qualifier is provided on @Autowired?

@Service
//@Qualifier("Parent")
class ParentRunner;

@Service
@Qualifier("Child")
class ChildRunner extends ParentRunner;

The following does at least not work:

@Autowired
//@Qualifier("Parent")
private ParentRunner runner;
Atrocious answered 29/1, 2014 at 10:54 Comment(2)
You can mark one implementation with @Primary which will then be used as default. See docs.spring.io/spring/docs/current/javadoc-api/org/…Okun
Great that works! Would you mind adding this as an answer, not as comment, so I can accept it?Atrocious
O
8

You can mark one implementation with @Primary which will then be used as default. When using xml you can use the primary element inside the bean element to set an instance to the primary bean instance to use.

See http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/Primary.html

Okun answered 29/1, 2014 at 11:0 Comment(2)
The problem with javax Primary is that this will not be a default that can be overriden. (Except through xml config) So from my point of view its not a default but the only implementation active ones this class is in the classpath. There is a jira entry which requests using priority reather than primary to allow declaring a higher precedence than the default implementation: jira.springsource.org/browse/SPR-10548Engrail
@Primary only kicks in if there are multiple candidates for resolving. If you specify a specific @Qualifier it should match only a single candidate and then that one should be used.Okun

© 2022 - 2024 — McMap. All rights reserved.