主体流程
注册 ConversionService ↓
注册 EmbeddedValueResolver ↓
实例化 Initialize LoadTimeWeaverAware beans ↓
取消临时的类加载器 ↓
冻结 bean 定义元数据
代码块-注册 ConversionService
可以通过转换服务进行数据类型的转换,如:String 转换为 Date 。
// 注册 ConversionService
if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
beanFactory.setConversionService(
beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
}
代码演示
首先准备一个转换器,用于将 String 转换成 LocalDateTime。
@Component
public class OrgConverter implements Converter<String, LocalDateTime> {
@Override
public LocalDateTime convert(String source) {
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
return LocalDateTime.parse(source, dateTimeFormatter);
}
}
注册转换器
@Configuration
public class ConverterServiceConfig {
@Bean
public ConversionServiceFactoryBean conversionService() {
ConversionServiceFactoryBean conversionServiceFactoryBean = new ConversionServiceFactoryBean();
HashSet<Object> set = new HashSet<>();
set.add(new OrgConverter());
conversionServiceFactoryBean.setConverters(set);
return conversionServiceFactoryBean;
}
}
测试
public class OrgConverterApp {
public static void main(String[] args) {
// 根据注解加载bean
AnnotationConfigApplicationContext context
= new AnnotationConfigApplicationContext("cn.lichenghao.converter");
ConversionService conversionService = context.getBeanFactory().getConversionService();
LocalDateTime convert = conversionService.convert("2023-01-21 13:36:28", LocalDateTime.class);
System.out.println(convert);
}
}
代码块-注册值解析器
// 如果没有值解析器,就添加一个
if (!beanFactory.hasEmbeddedValueResolver()) {
beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
}
代码块-Initialize LoadTimeWeaverAware beans
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {
getBean(weaverAwareName);
}
代码块-取消临时的类加载器
// 取消临时的类加载器
beanFactory.setTempClassLoader(null);
代码块-冻结元数据
beanFactory.freezeConfiguration();
public void freezeConfiguration() {
this.configurationFrozen = true;
this.frozenBeanDefinitionNames = StringUtils.toStringArray(this.beanDefinitionNames);
}