FactoryBean和BeanFactory

前言:
    这是一个很容易被问到的关于Spring的面试题。

    两个特别像,但是功能却千差万别。

    有关于BeanFactory,我们都知道,这是Spring容器的基础实现类,它负责生产和管理Bean的一个工厂。当然BeanFactory只是一个接口,它的常用实现有XmlBeanFactory、DefaultListableBeanFactory、ApplicationContext等。

    那么今天的重点来了,什么是FactoryBean呢?

1.FactoryBean
    FactoryBean是一个接口,具体方法如下:

public interface FactoryBean<T> {
 
    T getObject() throws Exception;
 
    Class<?> getObjectType();
 
    boolean isSingleton();
}


    它的作用是什么呢,使用在哪些场景呢?Spring官方文档中给出了答案

If you have complex initialization code that is better expressed in Java as opposed to a (potentially) verbose amount of XML, you can create your own FactoryBean, write the complex initialization inside that class, and then plug your custom FactoryBean into the container.
    简单表达就是:我们常规的Bean都是使用Class的反射获取具体实例,如果Bean的获取过程比较复杂,那么常规的xml配置需要配置大量属性值,这个时候我们就可以使用FactoryBean,实现这个接口,在其getObject()方法中初始化这个bean。

    话不多说,下面用一个示例来展示一下其用法

 

2.FactoryBean示例
    1.创建一个StudentFactoryBean

public class StudentFactoryBean implements FactoryBean {
 
    @Override
    public Object getObject() throws Exception {
 
        Student student = new Student();
        student.setAge(22);
        student.setName("jj");
        student.setId(10);
        
        return student;
    }
 
    // 对象具体类型
    @Override
    public Class<?> getObjectType() {
        return Student.class;
    }
 
    // 是否单例
    @Override
    public boolean isSingleton() {
        return true;
    }
}

2.在SpringConfiguration中添加该bean

@Configuration
public class SpringConfiguration {
    @Bean
    public StudentFactoryBean studentFactoryBean(){
        return new StudentFactoryBean();
    }
}
    3.测试

@Test
public void testStudentFactoryBean(){
    AnnotationConfigApplicationContext applicationContext
        = new AnnotationConfigApplicationContext(SpringConfiguration.class);
 
    Student student = (Student) applicationContext.getBean("studentFactoryBean");
    System.out.println(student);
}
 
// res
Student(id=10, name=test:jj, age=22)


    总结:成功的调用了StudentFactoryBean.getObject()方法

3.总结FactoryBean和BeanFactory

    BeanFactory:工厂类接口,Spring容器的核心接口,实例化bean、配置bean之间的依赖关系

    FactoryBean:实例化bean过程比较复杂时可以考虑使用
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值