文章目录
1 FactoryBean介绍
通过FactoryBean也可以容器中添加Bean
public interface FactoryBean<T> {
// // 返回一个对象,添加到工厂中
T getObject() throws Exception;
// 返回对象的类型
Class<?> getObjectType();
// 是否单例: true 单例 false 多例
boolean isSingleton();
}
2 演示
- Bean定义: 定义一个Address类
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Address {
private String address;
}
- 实现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;
}
}
- 配置该HangZhouAddressBeanFactory
@Configuration
@Import(value = MyImportBeanDefinitionRegistrar.class)
public class MainConfig {
@Bean
public HangZhouAddressBeanFactory hangZhouAddressBeanFactory(){
return new HangZhouAddressBeanFactory();
}
}
- 测试
@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));
}