最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Spring @Conditional注解原理解析

 更新時(shí)間:2019年11月20日 14:27:00   作者:聞窗  
這篇文章主要介紹了Spring @Conditional注解原理解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

這篇文章主要介紹了Spring @Conditional注解原理解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

@Conditional是Spring4新提供的注解,它的作用是根據(jù)某個(gè)條件加載特定的bean。

我們需要?jiǎng)?chuàng)建實(shí)現(xiàn)類(lèi)來(lái)實(shí)現(xiàn)Condition接口,這是Condition的源碼

public interface Condition {
  boolean matches(ConditionContext var1, AnnotatedTypeMetadata var2);
}

所以我們需要重寫(xiě)matches方法,該方法返回boolean類(lèi)型。

首先我們準(zhǔn)備根據(jù)不同的操作系統(tǒng)環(huán)境進(jìn)行對(duì)容器加載不同的bean,先創(chuàng)建Person

public class Person {
}

創(chuàng)建實(shí)現(xiàn)類(lèi)LinuxCondition和WindowCondiction,

LinuxCondition:

public class WindowCondiction implements Condition {
  @Override
  public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
   return true;
  }
}

WindowCondiction:

public class LinuxCondition implements Condition {
  @Override
  public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {

    return true;
  }
}

配置類(lèi):給相應(yīng)的bean加上 @Conditional注解,里面的括號(hào)將返回boolean類(lèi)型,返回true則加載bean

@Configuration
public class MainConfig {

  @Profile("window")
  @Conditional(WindowCondiction.class)
  @Bean
  public Person person01(){
    return new Person("李思",30);
  }

  @Profile("linux")
  @Conditional(LinuxCondition.class)
  @Bean
  public Person person02(){
    return new Person("wangwu",35);
  }
}

測(cè)試:現(xiàn)在是按照l(shuí)inux環(huán)境,@Profile注解先匹配linux的bean,再根據(jù)@Conditional 返回的類(lèi)型判斷是否加載bean,這里都設(shè)置返回true,所以應(yīng)該打印

Person{name='wangwu', age=35}

public class CondictionTest {

  @Test
  public void test(){
    //創(chuàng)建容器
    AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
    //設(shè)置需要激活的環(huán)境
    applicationContext.getEnvironment().setActiveProfiles("linux");
    //設(shè)置主配置類(lèi)
    applicationContext.register(MainProfileConfig.class);
    //啟動(dòng)刷新容器
    applicationContext.refresh();

    String[] beanNamesForType = applicationContext.getBeanNamesForType(DataSource.class);
    for (String name : beanNamesForType){
      System.out.println(name);
    }
    applicationContext.close();
  }
}

如果把LinuxCondition的返回值該為false,會(huì)報(bào)找不到bean的異常

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.springbean.Person' available

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論

蛟河市| 陕西省| 都安| 神池县| 伊通| 沐川县| 宁海县| 康乐县| 宁乡县| 靖州| 义乌市| 浙江省| 藁城市| 泰州市| 广东省| 平远县| 崇信县| 揭西县| 富蕴县| 白城市| 佛学| 布尔津县| 天水市| 高雄市| 宜川县| 靖远县| 台北县| 开远市| 莱州市| 杂多县| 眉山市| 德安县| 宜阳县| 剑川县| 苍梧县| 阿荣旗| 汉川市| 历史| 大冶市| 师宗县| 伊宁市|