We have some beans that are conditional
@Service
@ConditionalOnProperties("${condition}")
class Foo {
...
}
We want to be able to autowire those bean based on the same condition, is there a way to do something like:
@Autowired(required="${condition}")
private Foo foo;
Is there a way to obtains such result using properties from application.yml ?
CodePudding user response:
You can create a Foo as bean with @ConditionalOnProperty(value = "condition", havingValue = "true")
like below
@Configuration
public class BasicConfig {
@Bean
@ConditionalOnProperty(value = "condition", havingValue = "true")
public Foo foo() {
return new Foo();
}
}
Inject this foo bean as
@Autowired(required = false)
private Foo foo;
@Autowired(required = false)
is for make this field as optional.
Whenever condition satisfied, here foo will have value otherwise it will be null.
CodePudding user response:
You can try using SPEL.
For example: @Autowired(required="#{ systemProperties['user.region'] }")