原文网址:Spring--条件注入(条件装配)--实例_IT利刃出鞘的博客-CSDN博客
简介
说明
本文用实例介绍Spring的条件注入的用法。
@Component、@Configuration+@Bean都可以与条件注入的注解结合。
相关网址
Spring--条件注入(条件装配)--详解_IT利刃出鞘的博客-CSDN博客
@Component + 条件注解
Bean
package com.example.config;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
@Component
@ConditionalOnProperty(name = "custom.myComponent.enabled", havingValue = "true")
public class MyComponent {
public MyComponent() {
System.out.println("[MyComponent#MyComponent]");
}
}
application.yml
custom:
myComponent:
enabled: true
运行结果:
[MyComponent#MyComponent]
若将application.yml的custom.myComponent.enabled去掉,或者设置为非true值,则不会输出上边的运行结果。
@Configuration + @Bean + 条件注解
上边是文章的部分内容,为便于维护,全文已转移到此网址:Spring-条件注入(条件装配)-实例 - 自学精灵