前几块代码都是为了后面的实例化做准备。

主体流程

注册 ConversionService ↓
注册 EmbeddedValueResolver ↓
实例化 Initialize LoadTimeWeaverAware beans ↓
取消临时的类加载器 ↓
冻结 bean 定义元数据

代码块-注册 ConversionService

可以通过转换服务进行数据类型的转换,如:String 转换为 Date 。

  1. // 注册 ConversionService
  2. if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
  3. beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
  4. beanFactory.setConversionService(
  5. beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
  6. }

代码演示
首先准备一个转换器,用于将 String 转换成 LocalDateTime。

  1. @Component
  2. public class OrgConverter implements Converter<String, LocalDateTime> {
  3. @Override
  4. public LocalDateTime convert(String source) {
  5. DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
  6. return LocalDateTime.parse(source, dateTimeFormatter);
  7. }
  8. }

注册转换器

  1. @Configuration
  2. public class ConverterServiceConfig {
  3. @Bean
  4. public ConversionServiceFactoryBean conversionService() {
  5. ConversionServiceFactoryBean conversionServiceFactoryBean = new ConversionServiceFactoryBean();
  6. HashSet<Object> set = new HashSet<>();
  7. set.add(new OrgConverter());
  8. conversionServiceFactoryBean.setConverters(set);
  9. return conversionServiceFactoryBean;
  10. }
  11. }

测试

  1. public class OrgConverterApp {
  2. public static void main(String[] args) {
  3. // 根据注解加载bean
  4. AnnotationConfigApplicationContext context
  5. = new AnnotationConfigApplicationContext("cn.lichenghao.converter");
  6. ConversionService conversionService = context.getBeanFactory().getConversionService();
  7. LocalDateTime convert = conversionService.convert("2023-01-21 13:36:28", LocalDateTime.class);
  8. System.out.println(convert);
  9. }
  10. }

代码块-注册值解析器

  1. // 如果没有值解析器,就添加一个
  2. if (!beanFactory.hasEmbeddedValueResolver()) {
  3. beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
  4. }

代码块-Initialize LoadTimeWeaverAware beans

  1. String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
  2. for (String weaverAwareName : weaverAwareNames) {
  3. getBean(weaverAwareName);
  4. }

代码块-取消临时的类加载器

  1. // 取消临时的类加载器
  2. beanFactory.setTempClassLoader(null);

代码块-冻结元数据

  1. beanFactory.freezeConfiguration();
  2. public void freezeConfiguration() {
  3. this.configurationFrozen = true;
  4. this.frozenBeanDefinitionNames = StringUtils.toStringArray(this.beanDefinitionNames);
  5. }