Spring 使用FactoryBean注册组件
2019-03-26 本文已影响0人
Godlike_4029
- 实现FactoryBean 接口
public class ColorFactoryBean implements FactoryBean {
/**
* 返回一个Color 对象, 这个对象会添加到容器中
* @return
* @throws Exception
*/
@Override
public Object getObject() throws Exception {
return new Color();
}
@Override
public Class<?> getObjectType() {
return Color.class;
}
/**
* 控制是否返回单实例,返回true 是单实例
*
* @return
*/
@Override
public boolean isSingleton() {
return true;
}
}
isSingleton() 方法返回 true 表示该bean 在容器中是单实例存在的,反之亦然
- 测试代码
@Test
public void testFactoryBean(){
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig2.class);
Object factroyBean = applicationContext.getBean("colorFactoryBean");
System.out.println(factroyBean.getClass());
Map<String, Color> beansOfType = applicationContext.getBeansOfType(Color.class);
System.out.println(beansOfType);
//如果想获取工厂bean的本身
Object bean = applicationContext.getBean("&colorFactoryBean");
System.out.println(bean);
}
- 测试结果
class com.spring.annotation.bean.Color
{com.spring.annotation.bean.Color=com.spring.annotation.bean.Color@327b636c, colorFactoryBean=com.spring.annotation.bean.Color@45dd4eda}
com.spring.annotation.bean.ColorFactoryBean@60611244
Process finished with exit code 0
注意: 虽然我们按照bean的名字获取bean,applicationContext.getBean("colorFactoryBean"); 但实际上容器中存在的是工厂返回的baen Color
如果我们想获取工厂bean的本身 Object bean = applicationContext.getBean("&colorFactoryBean");