Spring 提供的FactoryBean
一、FactoryBean
接口FactoryBean的实现类,用于向容器中注册Bean
二、FactoryBean案例
1、项目结构
2、Persion
public class Persion {
}
3、Bean注册配置类BeanConfig
import org.springframework.context.annotation.*;
/**
* @Configuration 注解:告诉Spring这是一个配置类
*
* 配置类 == 配置文件(beans.xml文件)
*
*/
@Configuration
public class BeanConfig {
@Bean
public MyFactoryBean myFactoryBean(){
return new MyFactoryBean();
}
}
4、FactoryBean实现类
import com.dashu.bean.Persion;
import org.springframework.beans.factory.FactoryBean;
public class MyFactoryBean implements FactoryBean<Persion> {
/**
*
* 返回一个对象,这个对象会添加到容器
*
* @return
* @throws Exception
*/
@Override
public Persion getObject() throws Exception {
return new Persion();
}
/**
* 返回对象的类型
* @return
*/
@Override
public Class<?> getObjectType() {
return Persion.class;
}
/**
* 用于判断该Bean时单例还是多例
*
* 返回值:
* true:这个Bean是单实例,每次获取都是同一个bean
* false:这个Bean是多实例,每次获取都会创建一个新的bean
*
* 默认返回值:true
*
*
* @return
*/
@Override
public boolean isSingleton() {
return true;
}
}
5、测试类
import com.dashu.config.BeanConfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
//加载配置类
AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(BeanConfig.class);
//获取成功注册到容器中的所有Bean的名称
String[] beanDefinitionNames = annotationConfigApplicationContext.getBeanDefinitionNames();
//遍历Bean的名称
for (String name : beanDefinitionNames){
System.out.println(name);
}
System.out.println("----------------------");
/**
* 通过遍历的Bean的名称,可以看到myFactoryBean被注册到了容器
*
* 当我们通过名称myFactoryBean获取实例时
*
* 我们得到的是 class com.dashu.bean.Persion 的实例
*
* 可知使用FactoryBean,默认获取到的是工厂Bean调用getObject创建的对象
*
*/
Object myFactoryBean = annotationConfigApplicationContext.getBean("myFactoryBean");
System.out.println(myFactoryBean.getClass());
System.out.println("----------------------");
/**
* 在工厂Bean中,我们设置方法isSingleton的返回值为true,为单实例
*
* 可以看到多次获取到的实例都为同一个
*
*/
Object myFactoryBean2 = annotationConfigApplicationContext.getBean("myFactoryBean");
System.out.println(myFactoryBean == myFactoryBean2);
System.out.println("----------------------");
/**
* 若想获取到工厂Bean的实例,则只需在名称myFactoryBean前加上一个字符 &
*
* 这样就可以获取到工厂Bean的实例
*
*/
Object myFactoryBean3 = annotationConfigApplicationContext.getBean("&myFactoryBean");
System.out.println(myFactoryBean3.getClass());
}
}