[Spring Boot Architecture] condition notes the use @Conditional

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/sinat_27933301/article/details/100857814

  Spring Boot is based on the contents of the configuration file, decide whether to create a bean, as well as how to create a Spring bean into the container, and Spring boot automated configuration of the core control is @Conditional comment.

1, the new EncodingConverter interface, and implement two classes.

public interface EncodingConverter {
}
public class GBKEncodingConverter implements EncodingConverter {
}
public class UTF8EncodingConverter implements EncodingConverter {
}

2, GBKCondition class

public class GBKCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        String encoding = System.getProperty("file.encoding");
        if ("gbk".equals(encoding.toLowerCase())) {
            return true;
        }
        return false;
    }
}

3, UTF8Condition class

public class UTF8Condition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        String encoding = System.getProperty("file.encoding");
        if ("utf-8".equals(encoding.toLowerCase())) {
            return true;
        }
        return false;
    }
}

4, EncodingConverterConfig configuration class

@SpringBootConfiguration
public class EncodingConverterConfig {

    @Bean
    @Conditional(UTF8Condition.class)
    public EncodingConverter createUTF8Converter() {
        return new UTF8EncodingConverter();
    }

    @Bean
    @Conditional(GBKCondition.class)
    public EncodingConverter createGBKConverter() {
        return new GBKEncodingConverter();
    }
}

5, BootConditionConfigApplication class

@SpringBootApplication
public class BootConditionConfigApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(BootConditionConfigApplication.class, args);
                
		//获取该接口所有实现类的Bean
        Map<String, EncodingConverter> beansOfType = context.getBeansOfType(EncodingConverter.class);
        System.out.println(beansOfType);
        System.out.println(System.getProperty("file.encoding"));

        context.close();
    }
}

6, the console output

{createUTF8Converter=com.boot.condition.bootconditionconfig.converter.UTF8EncodingConverter@263f04ca}
UTF-8

Guess you like

Origin blog.csdn.net/sinat_27933301/article/details/100857814
Recommended