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

1221855-20181128164810338-1152124705.png

转载于:https://www.cnblogs.com/Grand-Jon/p/10025359.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值