What is the difference between FactoryBean, which is often asked in Spring interviews, and other beans?

foreword

In spring, FactoryBean is definitely a magical existence. It is often confused with BeanFactory, and it has become a question that is often asked during the interview process. In fact, FactoryBean and BeanFactory are well understood, and you can master certain skills.

first acquaintance

FactoryBean is translated as a factory bean, and BeanFactory is translated as a bean factory. The former is a bean in the bean factory beanFactory, but this bean is different from the general bean. It has its own special features. Where is it special? The interface of FactoryBean is provided in spring,

package org.springframework.beans.factory;

import org.springframework.lang.Nullable;


public interface FactoryBean<T> {

    
    @Nullable
    T getObject() throws Exception;

    
    @Nullable
    Class<?> getObjectType();

    
    default boolean isSingleton() {
        return true;
    }

}

The FactoryBean interface is very simple, it provides three methods getObject, getObjectType, isSingleton. It is these three methods that have become the basis of many functions in spring. Searching the source code of the entire spring can find many FactoryBeans. In addition to those provided by spring itself, when integrating with some frameworks, there are also the shadows of FactoryBeans, such as with mybatis. SqlSessionFactoryBean during integration,

usage

Here we take the springboot environment as an example to demonstrate the usage of FactoryBean. If you need the source code, you can follow the official account [Beidiao Programmer] and chat with me privately.

The custom FactoryBean only creates a new Student object in the getObject method and returns the object; rewrites the toString method for testing.

package com.example.myDemo.component;

import com.example.myDemo.po.Student;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.stereotype.Component;

@Component
public class MyFactoryBean implements FactoryBean<Student> {

    @Override
    public Student getObject() throws Exception {

        Student student=new Student();
        return student;
    }

    @Override
    public Class<?> getObjectType() {
        return null;
    }

    @Override
    public String toString() {
        return "MyFactoryBean{}";
    }
}

The following is the Student class, which simply has two properties and rewrites the toString method.

package com.example.myDemo.po;

public class Student {
    private String name;
    private String code;

    public Student(String name, String code) {
        this.name = name;
        this.code = code;
    }

    public Student() {
    }

    @Override
    public String toString() {
        return "Student{}";
    }
}

Here is the test method,

package com.example.myDemo;

import com.example.myDemo.component.MyFactoryBean;
import com.example.myDemo.po.Student;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.context.ApplicationContext;

@SpringBootApplication(exclude={DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
public class MyDemoApplication {

    public static void main(String[] args) {
        ApplicationContext ac=SpringApplication.run(MyDemoApplication.class, args);

        //获得Student对象
        Student stu=(Student) ac.getBean("myFactoryBean");
        //获得MyFactoryBean对象
        MyFactoryBean myFactoryBean=(MyFactoryBean) ac.getBean("&myFactoryBean");
        System.out.println("stu:"+stu);
        System.out.println("myFactoryBean:"+myFactoryBean);

    }

}

Take a look at the print results first.

The print result is strange that the Student object is obtained through "myFactoryBean" and the MyFactoryBean object is obtained through "&myFactoryBean". why is this

Functional explanation

After reading the above output results, many friends are very surprised. Yes, this is the magic of FactoryBean. In layman's terms, FactoryBean is a factory bean. It is a bean that can produce beans, and produces beans through its getObejct method. Of course, whether it is FactoryBean or the beans produced by FactoryBean are managed by spring, there is no problem, otherwise it cannot be obtained through the getBean method.

What is the use of FactoryBean so much as mentioned above. As mentioned earlier, the role of FactroyBean is to produce a bean. Here is a question. Spring is used to produce beans and manage beans. Why should there be FactoryBean? The real purpose of FactoryBean is to make Developers define those complex beans themselves and hand them over to spring for management. If many variables are to be initialized in the bean and many operations are to be performed, it is difficult to use spring's automatic assembly, so spring developers hand over these tasks to gave us. A common example is that when mybatis and spring are integrated, there is such a FactoryBean named SqlSessionFactoryBean. The purpose of this FactoryBean is to return a spring-managed SqlSessionFactory. Anyone who has used mybatis knows that to create a sqlSessionFactory, many properties need to be configured. , so with SqlSessionFactoryBean, let's take a look at SqlSessionFactoryBean,

Look at the getObejct method of sqlSessionFactoryBean

public SqlSessionFactory getObject() throws Exception {
        if (this.sqlSessionFactory == null) {
            this.afterPropertiesSet();
        }

        return this.sqlSessionFactory;
    }

getObejctType method

public Class<? extends SqlSessionFactory> getObjectType() {
        return this.sqlSessionFactory == null ? SqlSessionFactory.class : this.sqlSessionFactory.getClass();
    }

isSingleton method

public boolean isSingleton() {
        return true;
    }

Summarize

This article mainly brings friends to understand the special bean of FactoryBean, its function is to produce beans. There is a question here. When using the getBean method, why is the return value of "myFactoryBean" and "&MyFactoryBean" passed in? One is the bean produced by FactoryBean and the other is FactorBean. The next part will reveal the secrets through the source code and reveal the secrets of the getObjectForBeanInstance method. things, welcome to pay attention.

Original link: 
http://www.cnblogs.com/teach/p/14951920.html

If you think this article is helpful to you, you can retweet, follow and support

Guess you like

Origin blog.csdn.net/m0_67645544/article/details/124451778