说明
本文用实例介绍Spring的条件注入的用法。
@Component、@Configuration+@Bean都可以与条件注入的注解结合。
@Component+条件注解Bean
application.yml
custom: myComponent: enabled: true
运行结果:
[MyComponent#MyComponent]
若将application.yml的custom.myComponent.enabled去掉,或者设置为非true值,则不会输出上边的运行结果。
@Configuration+@Bean+条件注解Bean
配置类
application.yml
custom: myComponent: enabled: true
运行结果:
[MyComponent#MyComponent]
若将application.yml的custom.myComponent.enabled去掉,或者设置为非true值,则不会输出上边的运行结果。
@Configuration+条件注解+@BeanBean
配置类
application.yml
custom: myComponent: enabled: true
运行结果:
[MyComponent#MyComponent]
若将application.yml的custom.myComponent.enabled去掉,或者设置为非true值,则不会输出上边的运行结果。
自定义Condition自定义的condition的matches方法返回值为true时,才会创建bean。
条件类
//判断当前系统是否是Mac
到此这篇关于Spring示例讲解条件注入方法的文章就介绍到这了,更多相关Spring条件注入内容请搜索七叶笔记以前的文章或继续浏览下面的相关文章希望大家以后多多支持七叶笔记!