Spring注解驱动开发 第六节 FactoryBean使用笔记
在这之前,如果一个类要注入到spring容器,是spring在启动时调用类的空构造方法,加载类并注入到spring容器,但是现在的FactoryBean是在容器启动时,调用FactoryBean的getObject方法加载这个类,所以它和以前的注入spring容器的方式还是有区别的。
//创建一个spring定义的FactoryBean
public class MyBeanFactory implements FactoryBean<Color> {
//获取Factory中返回的bean对象
public Color getObject() throws Exception {
return new Color();
}
//返回bean对象的类型
public Class<?> getObjectType() {
return Color.class;
}
//在工厂bean中是否是单实例,true是单实例,false是多实例
public boolean isSingleton() {
return true;
}
}
首先新建一个MyBeanFacroty类实现FactoryBean接口,重写getObject、getObjectTpey、isSingleton三个方法,其中getObject 是加载要注入spring容器的类的,getObjectType是表示这个类的类型,isSingleton方法表示这个bean是否是单实例,true是单实例,false是多实例。
@Configuration
public class MainConfig4 {
@Bean
public MyBeanFactory beanFactory(){
return new MyBeanFactory();
}
}
然后创建一个配置类,在容器中把刚才实现FactoryBean的类注入到spring容器,然后我们查看打印结果。
四月 23, 2019 1:28:27 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@2f410acf: startup date [Tue Apr 23 13:28:27 GMT+08:00 2019]; root of context hierarchy
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalRequiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
mainConfig4
beanFactory
class com.meng.pojo.Color
Process finished with exit code 0
可以看出容器中注入的时Color类而不是MyBeanFactory类,如果我们想获得工厂FacrotyBean怎么办。
@Test
public void test05(){
ApplicationContext context = new AnnotationConfigApplicationContext(MainConfig4.class);
String[] names = context.getBeanDefinitionNames();
for(String name : names){
System.out.println(name);
}
Object object = context.getBean("&beanFactory");
System.out.println(object.getClass());
}
需要在spring容器中获取bean的时候要在bean名称前面加上&。查看打印结果:
四月 23, 2019 1:30:08 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@2f410acf: startup date [Tue Apr 23 13:30:08 GMT+08:00 2019]; root of context hierarchy
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalRequiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
mainConfig4
beanFactory
class com.meng.beanfactory.MyBeanFactory
Process finished with exit code 0
可以看到MyBeanFactory被获取到了。