Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the difference between BeanFactory and FactoryBean in Spring

2025-01-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

Editor to share with you what is the difference between BeanFactory and FactoryBean in Spring. I hope you will get something after reading this article. Let's discuss it together.

There are two interfaces, BeanFactory and FactoryBean, in Spring, which are similar in name and easy to get confused.

1. BeanFactory

BeanFactory is an interface, which is the top-level specification of the factory in Spring and the core interface of SpringIoc containers. It defines general methods for managing Bean, such as getBean (), containsBean (), and so on. The containers of Spring are its specific implementations, such as:

DefaultListableBeanFactory

XmlBeanFactory

ApplicationContext

These implementation classes have different extensions from different dimensions.

1.1.Source code public interface BeanFactory {/ / A pair of escaped definitions of FactoryBean, because if the object retrieved by FactoryBean using the name of bean is a factory-generated object, / / if you need to get the factory itself, you need to escape String FACTORY_BEAN_PREFIX = "&"; / / according to the name of bean, get the bean instance Object getBean (String name) throws BeansException in the IOC container / / the bean instance is obtained according to the name and Class type of bean, and the type safety verification mechanism is added. T getBean (String name, @ Nullable Class requiredType) throws BeansException; Object getBean (String name, Object...) Args) throws BeansException; T getBean (Class requiredType) throws BeansException; T getBean (Class requiredType, Object...) Args) throws BeansException; / / provides the retrieval of bean to see if there is a bean boolean containsBean (String name) with this name in the IOC container; / / get the bean instance based on the bean name, and determine whether the bean is a singleton boolean isSingleton (String name) throws NoSuchBeanDefinitionException; boolean isPrototype (String name) throws NoSuchBeanDefinitionException; boolean isTypeMatch (String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException Boolean isTypeMatch (String name, @ Nullable Class typeToMatch) throws NoSuchBeanDefinitionException; / / get the Class type of bean instance @ Nullable Class getType (String name) throws NoSuchBeanDefinitionException; / / get the alias of bean. If the alias is retrieved according to the alias, the original name will also be retrieved from String [] getAliases (String name).

Get Bean (byName or byType) from the Ioc container

Retrieves whether the specified Bean is contained in the Ioc container

Judge whether Bean is a singleton

II. FactoryBean

First of all, it's a Bean, but it's not just a Bean. It is a factory Bean that can produce or modify the generation of objects, similar to factory patterns and decorator patterns in design patterns. It can produce an object when needed, and is not limited to itself, it can return any instance of Bean.

2.1.Source public interface FactoryBean {/ / get bean @ Nullable T getObject () throws Exception; / / get the type of object created by Bean factory @ Nullable Class getObjectType (); / / whether the object created by Bean factory is singleton pattern default boolean isSingleton () {return true;}}

As can be seen from the interfaces it defines, FactoryBean represents the responsibility of a factory. That is, if a Bean An implements the FactoryBean interface, then A becomes a factory. According to A's name, what is actually obtained is the object returned by the factory calling getObject (), not An itself. If you want to get an instance of factory An itself, you need to precede the name with a'& 'symbol.

GetObject ('name') returns the instance in the factory

GetObject ('& name') returns an instance of the factory itself

In general, bean does not have to implement the factory pattern on its own, and the Spring container acts as a factory; but in a few cases, the bean in the container is itself a factory to generate other bean instances. Other bean instances generated by the factory bean are no longer generated by the Spring container, so unlike the normal bean configuration, the class element is no longer required.

2.2, example

First define a Bean implementation FactoryBean interface

@ Componentpublic class MyBean implements FactoryBean {private String message; public MyBean () {this.message = "initialize the instance by constructor";} @ Override public Object getObject () throws Exception {/ / you don't have to return an instance of MyBean itself here, it can be an instance of any other object. / such as return new Student (). Return new MyBean ("create an instance through FactoryBean.getObject ()");} @ Override public Class getObjectType () {return MyBean.class;} public String getMessage () {return message;}}

MyBean implements two methods of the FactoryBean interface. GetObject () can return an instance of any object, where the test returns its own instance of MyBean and assigns a value to the message field before returning. Also assign a value to message in the constructor. Then in the test code, first get the Bean instance by name, print the content of message, and then get the instance and print the message content by & + name.

@ RunWith (SpringRunner.class) @ SpringBootTest (classes = TestApplication.class) public class FactoryBeanTest {@ Autowired private ApplicationContext context; @ Test public void test () {MyBean myBean1 = (MyBean) context.getBean ("myBean"); System.out.println ("myBean1 =" + myBean1.getMessage ()); MyBean myBean2 = (MyBean) context.getBean ("& myBean"); System.out.println ("myBean2 =" + myBean2.getMessage ()) System.out.println ("myBean1.equals (myBean2) =" + myBean1.equals (myBean2));}} myBean1 = initialize the instance through FactoryBean.getObject () myBean2 = initialize the instance myBean1.equals (myBean2) = false2.3 by construction method, use the scene

Having said so much, why is there such a thing as FactoryBean? is there any specific function?

One of the most typical applications of FactoryBean in Spring is to create proxy objects for AOP.

We know that AOP is actually a proxy object created by Spring at run time, that is, it is created at run time rather than defined in the first place, which is in line with the factory method pattern. More vividly, the AOP proxy object creates a proxy object at run time through the reflection mechanism of Java, and weaves the corresponding method into the target method of the proxy object according to the business requirements. This object is called ProxyFactoryBean in Spring.

Therefore, FactoryBean provides a more flexible way for us to instantiate Bean, and we can create more complex Bean instances through FactoryBean.

III. Differences

Both of them are factories, but FactoryBean is essentially a Bean and is managed by BeanFactory.

BeanFactory is the top-level interface of the Spring container, and FactoryBean is more similar to the user-defined factory interface.

The difference between BeanFactory and FactoryBean is really easy to confuse, rote memorization is not good, it is best to understand it from the source level and in the context of spring.

After reading this article, I believe you have a certain understanding of "what is the difference between BeanFactory and FactoryBean in Spring". If you want to know more about it, you are welcome to follow the industry information channel. Thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report