3

I have a spring boot application in which I want to Autowire a bean for which implementation is specified in application.yaml. What is the best way to achieve it?

@Component
public class FooFormatter implements Formatter {}

@Component
public class BarFormatter implements Formatter {}

public class MyService {
    @Autowired
    @Qualifier("value_from_config")// The implementation is specified in application.yaml file
    private Formatter formatter;
}
A.K.G
  • 124
  • 6
  • 1
    Does this answer your question? [Passing variables to @Qualifier annotation in Spring](https://stackoverflow.com/questions/28589479/passing-variables-to-qualifier-annotation-in-spring) – GreyBeardedGeek Feb 05 '22 at 12:38

1 Answers1

1

The best way to achieve it is to use @ConditionalOnProperty.

So given the followings :

@Component
@ConditionalOnProperty(prefix = "app.formatter", name = "impl", havingValue = "foo",matchIfMissing = true)  
public class FooFormatter implements Formatter {

}

@Component
@ConditionalOnProperty(prefix = "app.formatter", name = "impl", havingValue = "bar")    
public class BarFormatter implements Formatter {

}

Then to enable FooFormatter only , configure the application properties as :

app.formatter.impl=foo

To enable BarFormatter only , configure the application properties as :

app.formatter.impl=bar

If no app.formatter.impl is defined in application properties , it will default to FooFormatter (because of the matchIfMissing = true)

Ken Chan
  • 84,777
  • 26
  • 143
  • 172