• Spring源码窥探之:FactoryBean


    1. 定义Fish实体类

    /**
     * @author 70KG
     * @Title: Fish
     * @Description:
     * @date 2018/7/22下午5:00
     * @From www.nmyswls.com
     */
    @Data
    public class Fish {
    
        private String name;
    
        private int age;
    
        public Fish(){}
    
        public Fish(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
    }

    2. 实现FactoryBean来注入实体类

    /**
     * @author 70KG
     * @Title: FactoryBeanRegist
     * @Description:
     * @date 2018/7/22下午8:06
     * @From www.nmyswls.com
     */
    public class FactoryBeanRegist implements FactoryBean<Fish> {
    
        @Override
        public Fish getObject() throws Exception {
            return new Fish();
        }
    
        @Override
        public Class<?> getObjectType() {
            return Fish.class;
        }
    
        @Override
        public boolean isSingleton() {
            return true;
        }
    }

    3. 编写配置类

    /**
     * @author 70KG
     * @Title: FactoryBeanConfig
     * @Description:
     * @date 2018/7/22下午8:21
     * @From www.nmyswls.com
     */
    @Configuration
    public class FactoryBeanConfig {
    
        @Bean
        public FactoryBeanRegist getBean() {
            return new FactoryBeanRegist();
        }
    
    }

    4. 测试

    /**
     * @author 70KG
     * @Title: FactoryBean的测试类
     * @Description:
     * @date 2018/7/22下午8:22
     * @From www.nmyswls.com
     */
    public class Test01 {
    
        @Test
        public void test() {
    
            AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(FactoryBeanConfig.class);
            // 不加"&"获取到的是FactoryBean中的实例
            Object getBean1 = ac.getBean("getBean");
            // 加"&"获取到的是实现了FactoryBean接口的FactoryBeanRegist本身
            Object getBean2 = ac.getBean("&getBean");
            System.out.println(getBean1.getClass());
            System.out.println(getBean2.getClass());
    
        }
    
    }

    5. 测试结果

    class com.nmys.story.springCore.springioc.importBean.Fish
    class com.nmys.story.springCore.springioc.factoryBean.FactoryBeanRegist

    FactoryBean是用来向容器中注入Bean的接口。而BeanFactory是从容器中取Bean的接口。

  • 相关阅读:
    Docker常用命令
    CentOS7.8源码安装nginx
    CentOS7.8搭建STF
    Mac关闭系统安全保护(提示无权删除/usr/bin目录下的文件时)
    Mac本地安装Tcloud-后端
    Mac后台运行进程-终端退出不影响其后台运行
    Docker快速部署TCloud云测试平台--前端
    Docker快速部署TCloud云测试平台--后端
    【项目】项目组件索引
    Netty 直接内存(堆外内存)溢出分析
  • 原文地址:https://www.cnblogs.com/zhangjianbing/p/9820663.html
Copyright © 2020-2023  润新知