Spring之使用FactoryBean注册组件

在spring框架与其他框架整合中用到FactoryBean很多,下面举个例子简单介绍一下使用FactoryBean注册bean
首先是需要写一个待注册类

public class Color {

}

写一个类实现FactoryBean接口

package chd.condition;

import org.springframework.beans.factory.FactoryBean;

import spring.Color;

public class ColorFactoryBean implements FactoryBean<Color>{

	//返回一个对象,添加到容器中
	public Color getObject() throws Exception {
		// TODO Auto-generated method stub
		return new Color();
	}
	//返回对象的类型
	public Class<?> getObjectType() {
		// TODO Auto-generated method stub
		return Color.class;
	}
	
	//是否是单例?
	//true:这个bean是单例,在容器中保存一份
	//false:每次获取都活创建一个新的bean
	public boolean isSingleton() {
		// TODO Auto-generated method stub
		return true;
	}

}

配置类中使用@Bean注解注册一下实现类

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

测试类测试一下

	AnnotationConfigApplicationContext   applicationContext  =new AnnotationConfigApplicationContext(MainConfig2.class);		

	@Test
	public void Test3() {
		String[] names=applicationContext.getBeanDefinitionNames();
		for (String na : names) {
			System.out.println(na);
		}
		//查看一下注册bean的类型是spring.Color
		Object bean = applicationContext.getBean("colorFactoryBean");
		System.out.println("bean类型"+bean.getClass());
	}

结果如下(获取bean是Color类)
在这里插入图片描述
那么我想拿到工厂bean(实现类ColorFactoryBean)的本身,而不是获取Color的bean,怎么实现呢?
在测试类中写法如下(在实现类名前加上“&”符号)

	@Test
	public void Test3() {
		String[] names=applicationContext.getBeanDefinitionNames();
		for (String na : names) {
			System.out.println(na);
		}
		//查看一下注册bean的类型是spring.Color
		Object bean = applicationContext.getBean("colorFactoryBean");
		System.out.println("bean类型"+bean.getClass());
		//获取colorFactoryBean的bean 实现类名前加上“&”符号
		Object bean2 = applicationContext.getBean("&colorFactoryBean");
		System.out.println("bean类型"+bean2.getClass());
	}

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

微微笑再加油

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值