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);
    }

原文地址:https://www.cnblogs.com/Grand-Jon/p/10025359.html