spring注解版 使用FactoryBean(工厂Bean)注册组件

一般在容器中注册组件都使用@Bean或者之前讲的@Import,当然还有包扫描+组件标注注解的方法。今天学了一个工厂Bean的方式注册组件,正好也在学设计模式,研究研究

玩FactoryBean需要搞一个类去实现它,老规矩,类名MyFactoryBean

import org.springframework.beans.factory.FactoryBean;

import test.spring.po.ZhangSan;

public class MyFactoryBean implements FactoryBean<ZhangSan> {
	// 返回一个ZhangSan对象,这个对象会添加到容器中
	public ZhangSan getObject() throws Exception {
		return new ZhangSan();
	}

	public Class<?> getObjectType() {
		return ZhangSan.class;
	}

	// 是否单例
	public boolean isSingleton() {
		return false;
	}

}

当然还是需要@Bean

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(value = "top.blogs")
public class MainConfig {
	@Bean
	public MyFactoryBean getFactoryBean() {
		return new MyFactoryBean();
	}
}

最后搞个测试类(还是没习惯用junit)

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import test.spring.config.MainConfig;

public class Main {

	public static void main(String[] args) {
		ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
		Object bean1 = applicationContext.getBean("getFactoryBean");
		Object bean2 = applicationContext.getBean("getFactoryBean");
		System.out.println(bean1 == bean2);
	}

}

当然这里打印的是false,因为前面isSingleton这个方法我返回的是false。还有一点就是getBean("getFactoryBean") 获取的是ZhangSan对象而不是工厂对象,若想获取工厂对象需要在getFactoryBean 前加个& 也就是getBean("&getFactoryBean") ,这里是因为spring的BeanFactory接口为我们定义了FactoryBean前缀为&,如下图BeanFacoty截图

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值