Traditional Culture Encyclopedia - Traditional customs - FactoryBean of Spring

FactoryBean of Spring

Under normal circumstances, Spring uses the bean's class attribute to specify the implementation class to instantiate the bean through the reflection mechanism.

In some cases, the process of instantiating a bean is not complicated. If you follow the traditional method, you need to provide a large amount of configuration information in , and the flexibility of configuration is limited. In this case, you may get

A simple way.

Spring provides a factory interface of org.springframework.bean.FactoryBean. Users can customize the instantiated beans by implementing this interface.

The FactoryBean interface occupies an important position in the Spring framework, and Spring itself provides a particularly large number of FactoryBean implementations.

They hide the details of instantiating complex beans and bring convenience to upper-layer applications.

The source code of FactoryBean is as follows: Three methods are defined in this interface: When the class attribute configuration of in the configuration file implements FactoryBean, what is returned through the getBean() method is not FactoryBean itself, but FactoryBean's getObject()

The object returned by the method.

For example, when configuring the Student below in the traditional way, each attribute of the Student will correspond to a element tag.

If you use FactoryBean to implement it, it will be more flexible. You can specify configuration values ????for all properties of Student at once through the following comma delimiter method: With this StudentFactoryBean, you can use the following method in the configuration file

StudentBean is configured.

When getBean("student") is called, Spring discovers the return of the StudentFactoryBean#getObject() method through the reflection mechanism.

If you want to get an instance of StudentFactoryBean, you need to add the "&" prefix before the beanName when using the getBean(beanName) method, for example, getBean("&student") .