【Spring源码解析】组件注册-FactoryBean注册组件

实现

  1. 配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class PersonFactoryBean implements FactoryBean {
@Override
public Object getObject() throws Exception {
return new Person("刘德华", 55);
}

@Override
public Class<?> getObjectType() {
return Person.class;
}

@Override
public boolean isSingleton() {
return true;
}
}
  1. 注册
1
2
3
4
5
6
7
8
@Configuration
public class BeanConfig2 {

@Bean
public PersonFactoryBean personFactoryBean() {
return new PersonFactoryBean();
}
}
  1. 测试
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* bean的类型:class cn.idea360.bean.Person
* 工厂bean:class cn.idea360.bean.PersonFactoryBean
*/
@Test
public void test05() {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeanConfig2.class);

Object personFactoryBean = applicationContext.getBean("personFactoryBean");
System.out.println("bean的类型:" + personFactoryBean.getClass());

Object bean = applicationContext.getBean("&personFactoryBean");
System.out.println("工厂bean:" + bean.getClass());
}

最后

本篇到此结束,欢迎大家关注公众号【当我遇上你】。