19

Say I need to rely on several implementations of a Spring bean. I have one AccountService interface and two implementations: DefaultAccountServiceImpl and SpecializedAccountServiceImpl.

  1. How is this possible (injecting one or the other implementation) in Spring?

  2. Which implementation will the following injection use?

    @Autowired
    private AccountService accountService;
    
River
  • 8,585
  • 14
  • 54
  • 67
balteo
  • 23,602
  • 63
  • 219
  • 412

2 Answers2

21

Ad. 1: you can use @Qualifier annotation or autowire using @Resource as opposed to @Autowired which defaults to field name rather than type.

Ad. 2: It will fail at runtime saying that two beans are implementing this interface. If one of your beans is additionally annotated with @Primary, it will be preferred when autowiring by type.

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • Tomasz: I understand that I need to use `@Qualifier("specialized")` to specify the implementation that is going to be injected. Then if I define my service using java (instead of xml) how do I specify which qualifier it has? Will this do: `@Service("specialized")`? – balteo Aug 02 '12 at 12:24
  • 3
    @balteo: yes. Either assign service name manually in `@Service` annotation or take simple class name with first character lower cased: `@Qualifier("specializedAccountServiceImpl")`. – Tomasz Nurkiewicz Aug 02 '12 at 12:27
15
@Autowired
@Qualifier("impl1")
BaseInterface impl1;

@Autowired
@Qualifier("impl2")
BaseInterface impl2;

@Component(value="impl1")
public class Implementation1  implements BaseInterface {

}

@Component(value = "impl2")
public class Implementation2 implements BaseInterface {

}


For full code: https://github.com/rsingla/springautowire/
Rajeev Singla
  • 788
  • 6
  • 7
  • 2
    What if I want to switch implementation for all the places where I @Autowire the interface? I don't want to specify explicitly at all usage places. – Daniel Hári Mar 14 '17 at 22:19
  • 1
    You can use Spring expression using @value and put the value in property file (application.properties) and switch back and forth bean the Qualifiers. (I havent tried this in this particular case but i am sure its just a string that the annotation is taking, so it should work fine. – Rajeev Singla Mar 16 '17 at 22:51