溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Sring Boot怎么自動裝配

發(fā)布時間:2021-07-07 15:59:27 來源:億速云 閱讀:163 作者:chen 欄目:大數(shù)據(jù)

這篇文章主要介紹“Sring Boot怎么自動裝配”,在日常操作中,相信很多人在Sring Boot怎么自動裝配問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”Sring Boot怎么自動裝配”的疑惑有所幫助!接下來,請跟著小編一起來學(xué)習(xí)吧!

  • 注解模式裝配

    @sevice @Conrtroller @Repository @Component

    這幾個注解在Srping源碼的文章中已經(jīng)將結(jié)果了,這里就不在贅述了。

  • 條件(Condition)裝配

    Condition 注解作為條件,如果符合條件則將bean注入到IOC中,反之則不注入,實(shí)際是使用 @Conditional注解來實(shí)現(xiàn),繼承 Condition 接口,通過 matches 方法進(jìn)行邏輯判斷是否符合條件。

    1: 創(chuàng)建ConditionOnSysProperty注解

    /**
     * @Auther: lantao
     * @Date: 2019-07-18 17:52
     * @Company: 隨行付支付有限公司
     * @maill: lan_tao@suixingpay.com
     * @Description: TODO
     */
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.TYPE, ElementType.METHOD})
    @Documented
    @Conditional({SysPropertyCondition.class})
    public @interface ConditionOnSysProperty {
    
        String value() default "lantao";
    }


    2:創(chuàng)建@Condtional所需要的條件 SysPropertyCondition

    /**
     * @Auther: lantao
     * @Date: 2019-07-18 17:52
     * @Company: 隨行付支付有限公司
     * @maill: lan_tao@suixingpay.com
     * @Description: TODO
     */
    public class SysPropertyCondition implements Condition {
    
        /**
         * 匹配方法
         *
         * @param context
         * @param metadata
         * @return
         */
        @Override
        public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
            // 獲取 ConditionOnSysProperty 注解的屬性
            Map<String, Object> attributes = metadata.getAnnotationAttributes(ConditionOnSysProperty.class.getName());
    
            String value = String.valueOf(attributes.get("value"));
    
            // 獲取本機(jī)的user.name值
            String propertieValue = System.getProperties().get("user.name").toString();
    
            // 對比
            return value.equals(propertieValue);
        }
    }


    3:創(chuàng)建COnditionBootStrap測試

    /**
     * @Auther: lantao
     * @Date: 2019-07-18 17:44
     * @Company: 隨行付支付有限公司
     * @maill: lan_tao@suixingpay.com
     * @Description: TODO
     */
    public class ConditionBootStrap {
    
        @Bean
        // 這了因?yàn)関alue是lantao, 正好user.name也是lantao,所以條件成立,會將bean注入到ioc中
        @ConditionOnSysProperty(value = "lantao")
        private String helloWorld() {
            return "Hello World ! Condition";
        }
    
    
        public static void main(String[] args) {
            // 這種方式可以不使用 SpringBootApplication 注解
            ConfigurableApplicationContext context = new SpringApplicationBuilder(ConditionBootStrap.class).run(args);
    
            // 獲取名為 helloWorld 的Bean,判斷 ConditionOnSysProperty 條件是否生效
            String helloWorld = context.getBean("helloWorld", String.class);
    
            System.out.println(helloWorld);
    
            // 關(guān)閉
            context.close();
        }
    }
    
    結(jié)果:
    Hello World ! Condition


  • @Enable 模塊裝配

    Eanble注解內(nèi)部使用@Importbean注入到ioc中,@import注解中可以直接放入bean,也可以做更靈活的配置,使用繼承了ImportSeletor接口的bean,可以根據(jù)@Enable注解的屬性(attrbutes)進(jìn)行靈活的動態(tài)判斷

    1: 創(chuàng)建 EnableHelloWorld

    /**
     * @Auther: lantao
     * @Date: 2019-07-18 18:03
     * @Company: 隨行付支付有限公司
     * @maill: lan_tao@suixingpay.com
     * @Description: TODO
     */
    
    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    // 直接使用無法靈活判斷
    //@Import(TestConfiguration.class)
    
    // 使用 HelloWorldImportSeletor 可以有更靈活的判斷
    @Import(HelloWorldImportSeletor.class)
    public @interface EnableHelloWorld {
    
        String name() default "lantao";
    }


    2: 創(chuàng)建TestConfiguration和Test1Configuration

    public class TestConfiguration {
        @Bean
        private String helloWorld() {
            return "hello World! Enable";
        }
    }
    
    public class Test1Configuration {
        @Bean
        public String buzhidao() {
            return "不知道";
        }
    }


    3: 創(chuàng)建HelloWorldImportSeletor

    /**
     * @Auther: lantao
     * @Date: 2019-07-19 09:55
     * @Company: 隨行付支付有限公司
     * @maill: lan_tao@suixingpay.com
     * @Description: TODO
     */
    public class HelloWorldImportSeletor implements ImportSelector {
    
        @Override
        public String[] selectImports(AnnotationMetadata importingClassMetadata) {
            // 獲取EnableHelloWorld注解的屬性
            Map<String, Object> attributes = importingClassMetadata.getAnnotationAttributes(EnableHelloWorld.class.getName());
            // 根據(jù)attributes 靈活判斷注入那個bean
            if ("lantao".equals(attributes.get("name"))) {
                System.out.println(TestConfiguration.class.getName());
                return new String[]{TestConfiguration.class.getName()};
            }
            System.out.println(TestConfiguration.class.getName());
            return new String[]{Test1Configuration.class.getName()};
        }
    }


    4:創(chuàng)建bootStrap測試

    /**
     * @Auther: lantao
     * @Date: 2019-07-18 18:04
     * @Company: 隨行付支付有限公司
     * @maill: lan_tao@suixingpay.com
     * @Description: TODO
     */
    @EnableHelloWorld
    //@EnableHelloWorld(name = "buzhidao")
    public class EnableBootStrap {
        public static void main(String[] args) {
    
            // 這種方式可以不使用 SpringBootApplication 注解
            ConfigurableApplicationContext context = new SpringApplicationBuilder(EnableBootStrap.class).run(args);
    
            // 獲取名為 helloWorld 的Bean,判斷 ConditionOnSysProperty 條件是否生效
            String helloWorld = context.getBean("helloWorld", String.class);
          //  這里可以獲取 bean名稱為 'buzhidao',需要注解@EnableHelloWorld(name = "buzhidao"),
          //  因?yàn)锧EnableHelloWorld的name默認(rèn)值是lantao,符合Condition的條件判斷
    //        String helloWorld = context.getBean("buzhidao", String.class);
    
            System.out.println(helloWorld);
    
            // 關(guān)閉
            context.close();
        }
    }
    
    結(jié)果:
    hello World! Enable


  • 工廠模式裝配

    自定義spring.factories,工廠模式裝配可以自定義starter。

    1: 創(chuàng)建SpringFactoriesConfiguration

    	/**
     * @Auther: lantao
     * @Date: 2019-07-22 10:10
     * @Company: 隨行付支付有限公司
     * @maill: lan_tao@suixingpay.com
     * @Description: TODO
     */ 
    @EnableHelloWorld
    @ConditionOnSysProperty(value = "lantao")
    @Configuration
    public class SpringFactoriesConfiguration {
        // 這里沒有寫 bean 的注入,直接引用 Condition 和 eanble 模塊注解。
    
        // eanble注解內(nèi)部使用import將bean注入到ioc中,@import注解中可以直接放入bean,也可以做更靈活的配置使用繼承了ImportSeletor接口的bean,
        // 可以根據(jù)enable注解的屬性(attrbutes)進(jìn)行靈活的動態(tài)判斷
    
        // Condition 注解作為條件,如果符合條件則將bean注入到IOC中,反之則不注入,實(shí)際是使用 @Conditional注解來實(shí)現(xiàn),通過繼承 Condition 接口,
        // 通過 matches 方法進(jìn)行邏輯判斷是否符合條件。
    }


    2: 創(chuàng)建 META-INF/spring.factories

    # Auto Configure
    org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
    com.lantao.springboot_leran.spring_factories_leran.config.SpringFactoriesConfiguration


    3: 創(chuàng)建 SpringFactoriesBootStrap 引導(dǎo)類

    /**
     * @Auther: lantao
     * @Date: 2019-07-19 16:01
     * @Company: 隨行付支付有限公司
     * @maill: lan_tao@suixingpay.com
     * @Description: TODO
     */
    @EnableAutoConfiguration
    public class SpringFactoriesBootStrap {
    
        public static void main(String[] args) {
            ConfigurableApplicationContext context = new SpringApplicationBuilder(SpringFactoriesBootStrap.class).run(args);
            String helloWorld = context.getBean("helloWorld", String.class);
            System.out.println(helloWorld);
            context.close();
        }
    }
    
    結(jié)果:
    hello World! Enable

到此,關(guān)于“Sring Boot怎么自動裝配”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識,請繼續(xù)關(guān)注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI