简体   繁体   中英

Configure @Autowired from application.yml

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?

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.

You can try using SPEL . For example: @Autowired(required="#{ systemProperties['user.region'] }")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM