美文网首页spring
Bean 生命周期

Bean 生命周期

作者: gstsyyb | 来源:发表于2020-05-25 20:38 被阅读0次

    技巧:
    1、processor 处理技巧
    2、chain 模式
    3、代理模式 + 建造模式

    一、spring 的 bean 对象是如何生成的,其中有哪些扩展点 ?

    image.png

    ClassPathXmlApplicationContext对象:


    image.png

    二、常见的扩展点
    1、BeanFactoryPostProcessor
    常见实现:PropertyResourceConfigurer、CustomEditorConfigurer
    2、BeanPostProcessor
    InstantiationAwareBeanPostProcessor
    常见实现:AutowiredAnnotationBeanPostProcessor
    3、ImportBeanDefinitionRegistrar

    三、基础的API

    DefaultListableBeanFactory beanfactory = new DefaultListableBeanFactory();

    //设置BeanFactoryPostProcessor处理器
    PropertyPlaceholderConfigurer propertyPlaceholderConfigurer = beanfactory.getBean(PropertyPlaceholderConfigurer.class);
    propertyPlaceholderConfigurer.postProcessBeanFactory(beanfactory);

    //设置BeanPostProcessor处理器
    AutowiredAnnotationBeanPostProcessor autowiredAnnotationBeanPostProcessor = new AutowiredAnnotationBeanPostProcessor();
    autowiredAnnotationBeanPostProcessor.setBeanFactory(beanfactory);
    beanfactory.addBeanPostProcessor(autowiredAnnotationBeanPostProcessor);

    //加载 bean 资源
    Resource res = new ClassPathResource("spring-bean.xml");
    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanfactory);
    reader.loadBeanDefinitions(res);

    //获取 Bean 对象
    Worker worker = beanfactory.getBean("worker", Worker.class);

    高级 API:
    1、动态注册 Bean 对象
    BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(User.class);
    beanDefinitionBuilder.addPropertyValue("name", "1");
    beanDefinitionBuilder.addPropertyValue("age", "2");
    BeanDefinition beanDefinition = beanDefinitionBuilder.getBeanDefinition();
    beanfactory.registerBeanDefinition("people", beanDefinition );

    User user = beanfactory.getBean("people", User.class);

    相关文章

      网友评论

        本文标题:Bean 生命周期

        本文链接:https://www.haomeiwen.com/subject/chpuahtx.html