SoFunction
Updated on 2025-04-13

How to create and get Bean objects using Spring's FactoryBean

Spring's FactoryBean creates and gets Bean objects

In the Spring framework, the FactoryBean interface provides a powerful mechanism to create complex bean instances.

Based on the provided code examples, this article will introduce in detail how to create bean objects through FactoryBeans, and show how to obtain these bean instances and the FactoryBean instances they belong to.

Sample code class

  1. Define the MyBean interface.

First, we define a simple interface MyBean, which contains a show method:

public interface MyBean {
    /**
      * Display information
      */
    void show();
}
  1. Implement the MyFactoryBean class.

We implement the FactoryBean interface to create an instance of MyBean type.

In this example, MyFactoryBean is responsible for creating and returning objects that implement the MyBean interface:

@Component
public class MyFactoryBean implements FactoryBean<MyBean> {

    // This myBean member variable can be ignored in this article and I use it myself for other purposes    private MyBean myBean;

    @Override
    public MyBean getObject() throws Exception {
        ("getObject");
        if(myBean == null) {
            myBean = new MyBean() {
                @Override
                public void show() {
                    ("");
                }
            };
        }
        return myBean;
    }

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

Here, MyFactoryBean uses anonymous inner class to implement the MyBean interface and rewritten the show method. There is a myBean member variable defined, which can be ignored, which I use for other purposes myself.

Get instance object from Spring container

In order to get the bean instance generated by MyFactoryBean or the MyFactoryBean itself from the Spring container, we need to get it firstApplicationContextThe instance itself, in the following code()It is a tool class I defined myself, assuming it can be obtained through itApplicationContextObject.

The following is a specific method to obtain the specific bean instances generated by the factory class itself and the factory class:

1. Get the specific bean instance created by FactoryBean:

// Get it through the name of the factory classMyBean myBean = (MyBean) ().getBean("myFactoryBean");
// Get through Bean type (if you have multiple factories and all produce MyBeans, please do not use Get, it will execute your multiple factory classes at the same time)MyBean myBean = ().getBean();

2. Get the example of the specific factory class FactoryBean that generates the Bean instance:

If you want to operate FactoryBean directly (for example, make some configuration tweaks), you can prefix the bean name by adding&As a prefix to get an instance of FactoryBean, this is the built-in naming rule for Spring:

// Get it through the name and & symbol of the factory classMyFactoryBean factoryBean = (MyFactoryBean) ().getBean("&myFactoryBean");
// Pass the factory classMyFactoryBean factoryBean = ().getBean();

Singleton and multi-instance

By rewritingisSingleton()Control the return value to determine whether the factory class returns an instance every time or the singleton bean is returned every time (the default value is true, single instance mode).

Note: The factory itself is a singleton, we usuallyWon'tSet up for factory classprototype, just rewrite when neededisSingleton()Method returnfalseTo implement multiple cases.

Summarize

Through the above steps, we can not only easily obtain the bean instance created by FactoryBean from the Spring container, but also the instance of this FactoryBean itself. This flexibility makes FactoryBean a powerful tool for dealing with complex bean creation logic. Whether you need to customize the bean creation process or want to have more granular control over the life cycle of the bean, FactoryBean can meet your needs.

In this way, developers can more flexibly manage and operate bean instances in Spring, improving the maintainability and scalability of their code.

The above is personal experience. I hope you can give you a reference and I hope you can support me more.