在項目中,有時會遇到我們的Configuration、Bean、Service等等的bean組件需要依條件按需加載的情況。那么Spring Boot怎么做的呢?它為此定義了許多有趣的條件,當我們將它們運用到我們的bean上時,就可以實現動態的加載控制了。
自動配置中使用的條件化注解
舉個栗子:公司同事做了一個公用的sso服務,業務系統可以選擇性進行集成。當配置文件設置sso.enabled = true時,啟動單點登錄。當設置sso.enabled = false時,使用spring-security。
- 配置文件
- spring-security配置類的條件化加載
/** * Security登錄認證配置 * @author hua.huang */ //@EnableWebSecurity // 啟動SpringSecurity @ConditionalOnProperty(value = "sso.enable",matchIfMissing = true,havingValue = "false") @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter{
ConditionalOnProperty的屬性說明
https://blog.csdn.net/shixin_li/article/details/80532866
@Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE, ElementType.METHOD }) @Documented @Conditional(OnPropertyCondition.class) public @interface ConditionalOnProperty { //數組,獲取對應property名稱的值,與name不可同時使用。 作用:value單獨使用時:當對應property名稱的值為false時,該configuration不生效;當對應property名稱的值為除false之外的值時,該configuration生效 String[] value() default {}; //字符串,property名稱的前綴,可有可無,可以與name組合使用 String prefix() default ""; //數組,property完整名稱或部分名稱(可與prefix組合使用,組成完整的property名稱),與value不可同時使用。 作用與value一樣 String[] name() default {}; //可與name、value(name和value不能同時存在)組合使用,比較獲取到對應property名稱的值與havingValue給定的值是否相同:如果相同,該configuration生效,反之,不生效 String havingValue() default ""; //缺少該property時是否可以加載。如果為true,沒有該property也會正常加載;反之報錯 boolean matchIfMissing() default false; //不需要管它 boolean relaxedNames() default true; }