06 sping注解开发-FactoryBean

1 FactoryBean介绍

通过FactoryBean也可以容器中添加Bean

public interface FactoryBean<T> {
	//  // 返回一个对象,添加到工厂中
    T getObject() throws Exception;
	// 返回对象的类型
    Class<?> getObjectType();
	// 是否单例: true 单例  false 多例
    boolean isSingleton();
}

2 演示

  1. Bean定义: 定义一个Address类
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Address {

    private String address;
}
  1. 实现FactoryBean接口导入一个杭州地址的Bean
public class HangZhouAddressBeanFactory implements FactoryBean<Address> {

    // 返回一个对象,添加到工厂中
    @Override
    public Address getObject() throws Exception {
        return new Address("杭州");
    }

    // 返回对象的类型
    @Override
    public Class<?> getObjectType() {
        return Address.class;
    }

    // 是否单例: true 单例  false 多例
    @Override
    public boolean isSingleton() {
        return true;
    }
}
  1. 配置该HangZhouAddressBeanFactory
@Configuration
@Import(value = MyImportBeanDefinitionRegistrar.class)
public class MainConfig {

        @Bean
        public HangZhouAddressBeanFactory hangZhouAddressBeanFactory(){
                return new HangZhouAddressBeanFactory();
        }
}
  1. 测试
 @Test
    public void test01(){
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
        Address bean1 = applicationContext.getBean(Address.class);
        // 注意:在配置文件注入的BeanFactory类型,但是通过bean的名字返回的值BeanFactory创建的对象
        Object bean2 = applicationContext.getBean("hangZhouAddressBeanFactory");
        Assert.assertThat(bean1,notNullValue());
        Assert.assertThat(bean1.getAddress(),equalTo("杭州"));
        // 单例
        Assert.assertThat(bean2==bean1,equalTo(Boolean.TRUE));


    }

注意: 在配置文件注入的BeanFactory类型,但是通过bean的名字返回的值BeanFactory创建的对象

如何获取这个HangZhouAddressBeanFactory呢?
加一个前缀即可: &

@Test
    public void test02(){
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
        Object bean2 = applicationContext.getBean("&hangZhouAddressBeanFactory");
        Assert.assertThat(bean2 instanceof HangZhouAddressBeanFactory,equalTo(Boolean.TRUE));
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值