zoukankan      html  css  js  c++  java
  • 11、组件注册-使用FactoryBean注册组件

    11、组件注册-使用FactoryBean注册组件

    package org.springframework.beans.factory;
    
    import org.springframework.lang.Nullable;
    
    public interface FactoryBean<T> {
    
    	@Nullable
    	T getObject() throws Exception;
    
    	@Nullable
    	Class<?> getObjectType();
    
    	default boolean isSingleton() {
    		return true;
    	}
    
    }
    
    

    11.1 实现FactoryBean接口

    package com.hw.springannotation.beans;
    
    import org.springframework.beans.factory.FactoryBean;
    
    /**
     * @Description 创建Spring 工厂bean
     * @Author hw
     * @Date 2018/11/28 16:32
     * @Version 1.0
     */
    public class ColorFactoryBean implements FactoryBean<Color> {
    
        /**
         * 返回一个color对象 ,这个对象会被添加到容器中
         *
         * @return
         * @throws Exception
         */
        public Color getObject() throws Exception {
            System.out.println("ColorFactoryBean……");
            return new Color();
        }
    
        /**
         * 返回Color对象的类型
         *
         * @return
         */
        public Class<?> getObjectType() {
            return Color.class;
        }
    
        /**
         * 控制是否单例
         *
         * @return true 单实例 false 多实例
         */
        public boolean isSingleton() {
            return true;
        }
    }
    
    

    11.2 MainConfig注入ColorFactoryBean

    @Bean
    public ColorFactoryBean colorFactoryBean() {
        return new ColorFactoryBean();
    }
    

    11.3 测试

        @Test
        public void testImport() {
            printBeans();
            //        System.exit(0);
    
            // 工厂bean调用的是 getObject创建的对象
            Object bean = applicationContext.getBean("colorFactoryBean");
            Object bean2 = applicationContext.getBean("colorFactoryBean");
            // 通过 & 前缀 获取工厂bean本身的对象
            Object bean3 = applicationContext.getBean("&colorFactoryBean");
            System.out.println(bean.getClass());
            System.out.println(bean3.getClass());
            System.out.println(bean == bean2);
        }
    
    

  • 相关阅读:
    LAMP
    监控和安全运维 1.8 zabbix服务端安装
    监控和安全运维 1.7 nagios配置邮件告警
    易道用车-拿什么说爱你
    unix exec族函数 关于参数的疑惑
    关于 Unix 用户权限及进程权限及 Saved set-user-id
    ANSI C中关于FILE流的一些
    Filco minila 的蛋疼。
    IIS32位,64位模式下切换
    Gvim+Emmet.vim 那些事。
  • 原文地址:https://www.cnblogs.com/Grand-Jon/p/10025359.html
Copyright © 2011-2022 走看看