使用FactoryBean注册组件

新建一个maven项目,导入jar包

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.3.12.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.12</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-api</artifactId>
        <version>RELEASE</version>
        <scope>compile</scope>
    </dependency>

</dependencies> 

实现FactoryBean接口

/**
 * 颜色工厂bean
 * @author: wangshuang
 * @date: 2020/5/21
 */
public class ColorFactoryBean implements FactoryBean<Color> {
    /**
     * 返回color对象,对象会添加到容器中
     * @return
     * @throws Exception
     */
    public Color getObject() throws Exception {
        System.out.println("ColorFactoryBean调用了getObject");
        return new Color();
    }

    /**
     *
     * @return
     */
    public Class<?> getObjectType() {
        return null;
    }

    /**
     * 是否是单例
     * true:是单例,在容器中只会保留一份
     * false:不是单例,每次获取都会创建一个新的
     * @return
     */
    public boolean isSingleton() {
        return false;
    }
}
@Configurable
public class MainConfig {

    @Bean
    public ColorFactoryBean colorFactoryBean() {
        return  new ColorFactoryBean();
    }
}
    public static void main(String[] args) {
        AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(MainConfig.class);

        Object beanByName = annotationConfigApplicationContext.getBean("colorFactoryBean");
        System.out.println("beanByName的类型"+beanByName.getClass());
        Object beanByName1 = annotationConfigApplicationContext.getBean("&colorFactoryBean");
        System.out.println("beanByName1的类型"+beanByName1.getClass());

        ColorFactoryBean beanByType = annotationConfigApplicationContext.getBean(ColorFactoryBean.class);
        System.out.println("beanByType的类型"+beanByType.getClass());
    }

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值