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;
}
CodePudding user response:
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)
