Spring Boot 是根据配置文件中的内容,决定是否创建 bean,以及如何创建 bean 到 Spring 容器中,而 Spring boot 自动化配置的核心控制,就是 @Conditional 注解。
1、新建EncodingConverter接口,以及两个实现类。
public interface EncodingConverter {
}
public class GBKEncodingConverter implements EncodingConverter {
}
public class UTF8EncodingConverter implements EncodingConverter {
}
2、GBKCondition类
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类
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配置类
@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类
@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、控制台输出
{createUTF8Converter=com.boot.condition.bootconditionconfig.converter.UTF8EncodingConverter@263f04ca}
UTF-8
转载:https://blog.csdn.net/sinat_27933301/article/details/100857814
查看评论