Spring扩展之四:BeanFactoryPostProcessor接口

BeanFactoryPostProcessor

1.介绍

允许对应用程序上下文的bean定义进行自定义修改的工厂钩子,列如:自定义配置文件中配置的Bean属性。

BeanFactoryPostProcessor可以与Bean定义进行交互并进行修改,但不能进行Bean实例化。这样做可能会导致bean实例化过早,从而违反了容器并造成了意外的副作用。如果需要bean实例交互,请考虑 BeanPostProcessor。

ApplicationContext在其Bean定义中自动检测BeanFactoryPostProcessor Bean,并在创建任何其他Bean之前应用它们,也可以通过编程方式注册到ConfigurableApplicationContext。

在ApplicationContext中自动检测到的BeanFactoryPostProcessor bean将根据PriorityOrdered和Ordered语义进行排序

通过ConfigurableApplicationContext以编程方式注册的BeanFactoryPostProcessor Bean将按注册顺序注册,将忽略通过实现PriorityOrdered或Ordered接口定义的顺序

// 函数式接口,只能有一个抽象的方法
@FunctionalInterface
public interface BeanFactoryPostProcessor {
    // 可以修改应用程序上下文的内部bean工厂。所有的bean定义都将被加载,但是还没有bean被实例化,允许重写或添加属性。
    void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;
}

2.使用

@Component
public class CustomBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        //打印当前容器内的Bean Definition
        String[] beanDefinitionNames = beanFactory.getBeanDefinitionNames();
        Arrays.stream(beanDefinitionNames).forEach(System.out::println);
        //修改Bean Definition信息
        for (String beanName : beanDefinitionNames) {
            if ("person".equals(beanName)) {
                BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
                MutablePropertyValues m = beanDefinition.getPropertyValues();
                m.addPropertyValue("name", "尼古拉斯赵四");
                System.out.println("--修改了name属性初始值了");
            }
        }
    }
}

3.注册点

refresh()方法下的
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
    PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
    ...
}
public static void invokeBeanFactoryPostProcessors(
        ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
    // 先将系统内置的BeanDefinitionRegistryPostProcessors遍历分组执行
    Set<String> processedBeans = new HashSet<>();
    if (beanFactory instanceof BeanDefinitionRegistry) {
        BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
        List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
        List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();

        for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
            if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
                BeanDefinitionRegistryPostProcessor registryProcessor =
                        (BeanDefinitionRegistryPostProcessor) postProcessor;
                registryProcessor.postProcessBeanDefinitionRegistry(registry);
                registryProcessors.add(registryProcessor);
            }
            else {
                regularPostProcessors.add(postProcessor);
            }
        }
        // 找到所有BeanDefinitionRegistryPostProcessor的实现类,按PriorityOrdered, Ordered分组排序执行
        List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
        String[] postProcessorNames =
                beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
        // 实现PriorityOrdered的
        for (String ppName : postProcessorNames) {
            if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
                currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                processedBeans.add(ppName);
            }
        }
        sortPostProcessors(currentRegistryProcessors, beanFactory);
        registryProcessors.addAll(currentRegistryProcessors);
        invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
        currentRegistryProcessors.clear();
        // Ordered
        postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
        for (String ppName : postProcessorNames) {
            if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
                currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                processedBeans.add(ppName);
            }
        }
        sortPostProcessors(currentRegistryProcessors, beanFactory);
        registryProcessors.addAll(currentRegistryProcessors);
        invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
        currentRegistryProcessors.clear();
        // PriorityOrdered, Ordered都没实现的
        boolean reiterate = true;
        while (reiterate) {
            reiterate = false;
            postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
            for (String ppName : postProcessorNames) {
                if (!processedBeans.contains(ppName)) {
                    currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                    processedBeans.add(ppName);
                    reiterate = true;
                }
            }
            sortPostProcessors(currentRegistryProcessors, beanFactory);
            registryProcessors.addAll(currentRegistryProcessors);
            invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
            currentRegistryProcessors.clear();
        }
        invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
        invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
    }
    else {
        // Invoke factory processors registered with the context instance.
        invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
    }

    // 找到所有BeanFactoryPostProcessor的实现类,按PriorityOrdered, Ordered分组排序执行
    String[] postProcessorNames =
            beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
    // 实现PriorityOrdered的
    List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
    List<String> orderedPostProcessorNames = new ArrayList<>();
    List<String> nonOrderedPostProcessorNames = new ArrayList<>();
    for (String ppName : postProcessorNames) {
        if (processedBeans.contains(ppName)) {
        }
        else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
            priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
        }
        else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
            orderedPostProcessorNames.add(ppName);
        }
        else {
            nonOrderedPostProcessorNames.add(ppName);
        }
    }
    sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
    invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
    // 实现Ordered的.
    List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
    for (String postProcessorName : orderedPostProcessorNames) {
        orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
    }
    sortPostProcessors(orderedPostProcessors, beanFactory);
    invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
    // PriorityOrdered, Ordered都没实现的BeanFactoryPostProcessors.
    List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
    for (String postProcessorName : nonOrderedPostProcessorNames) {
        nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
    }
    invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
    // 清除元数据缓存
    beanFactory.clearMetadataCache();
}

注册方式一:

//方式一,通过@Bean的方式初始化
@Configuration
public class SpringConfiguration {
    @Bean
    public CustomBeanFactoryPostProcessor customBeanFactoryPostProcessor() {
        return new CustomBeanFactoryPostProcessor();
    }
}

注册方式二:

// 方式二,通过@Component的方式初始化
@Component
public class CustomBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
    ...
}

4.触发点

 5.注意

BeanFactoryPostProcessor,会在创建Singleton Bean之前就被调用,所以并不能去修改Singleton Bean的信息;

实现PriorityOrdered接口的优先级高于实现Ordered接口的,没有实现排序接口的优先级最低。

BeanDefinitionRegistryPostProcessor

1.介绍

BeanFactoryPostProcessor的子接口,允许注册Bean Definition,在BeanFactoryPostProcessor之前执行。

public interface BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor {
    // 可以添加或修改应用程序上下文的内部bean工厂下的Bean Definition。所有的bean定义都将被加载,但是还没有bean被实例化,允许重写或添加属性。
    void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException;
}

2.使用

@Component
public class CustomBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {
    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        System.out.println("BeanDefinitionRegistryPostProcessor---postProcessBeanDefinitionRegistry");
        // 添加Bean Definition
        GenericBeanDefinition gbd = new GenericBeanDefinition();
        gbd.setBeanClass(testService.class);
        registry.registerBeanDefinition("xixi",gbd);
        // 修改Bean Definition
        BeanDefinition xixi = registry.getBeanDefinition("xixi");
        xixi.setBeanClassName("com.yue.test.test1Service");
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        //获取 Bean Definition
        System.out.println("BeanDefinitionRegistryPostProcessor---postProcessBeanFactory");
        BeanDefinition xixi = beanFactory.getBeanDefinition("xixi");
        System.out.println("xixi--"+xixi.toString());
    }
}

3.注册点、触发点同BeanFactoryPostProcessor

 

posted @ 2020-11-24 18:30  柒月丶  阅读(761)  评论(0)    收藏  举报