0

I have a situation where I want to enable clients to inject their own bean implementing a common interface into my class but otherwise use a default bean.

As an example:

public class TestClass {

    // Clients can inject this, otherwise use a default...
    @Autowired
    private ConfigInjector configInjector; 

}

My defined interface and default implementation:

public interface ConfigInjector {
    String getConfig();
}

@Component
public class DefaultConfigInjector implements ConfigInjector {
    public String getConfig() {
        return "DEFAULT CONFIG"
    } 
}

An external client wants to inject this implementation of my ConfigInjector interface:

@Component
public class ExternalConfigInjector implements ConfigInjector {
    public String getConfig() {
        return "EXTERNAL CONFIG"
    } 
}

Using @Autowired in TestClass, if the client attempts to use TestClass with his own ConfigInjector implementation (ExternalConfigInjector), then more than one ConfigInjector implementation will exist, resulting in a NoUniqueBeanDefinitionException exception.

So, how can I share my TestClass with clients allowing them to use their own ConfigInjector to override my default?

Kevin
  • 1
  • 2

1 Answers1

1
  1. you may use @ConditionalOnProperty annotation
  2. according to the name of the variable/argument
  3. using the @primary annotation
  4. using @Qualifier annotation

a recommended free course (1.5 h) name "Spring Framework And Dependency Injection For Beginners" at www.udemy.com explains all main issues and use cases.

nabeel
  • 319
  • 1
  • 9
  • The Primary annotation worked. My question is in fact similar to [this one](https://stackoverflow.com/questions/10534053/autowiring-two-beans-implementing-same-interface-how-to-set-default-bean-to-au?rq=1) which also suggests using the Primary annotation. Thanks! – Kevin Nov 13 '17 at 00:42
  • welcome, really recommend watching the short course :-) – nabeel Nov 13 '17 at 09:13