A, the BeanFactory

BeanFactory is an interface that is the top-level specification for factories in Spring. It is the core interface of the SpringIoc container and defines common methods for managing beans such as getBean() and containsBean(). Spring’s containers are all implementations of it such as:

DefaultListableBeanFactory

XmlBeanFactory

ApplicationContext

These implementation classes in turn have different extensions from different dimensions.

1.1, the source code

Public interface BeanFactory {// Escape the definition of a FactoryBean, because if you retrieve a FactoryBean by its name, the object you get is a factory-generated object, String FACTORY_BEAN_PREFIX = "&"; Object getBean(String name) throws BeansException; // Get the bean instance according to the bean name and Class type, add type safety verification mechanism. <T> T getBean(String name, @Nullable Class<T> requiredType) throws BeansException; Object getBean(String name, Object... args) throws BeansException; <T> T getBean(Class<T> requiredType) throws BeansException; <T> T getBean(Class<T> requiredType, Object... args) throws BeansException; Boolean containsBean(String name); Boolean containsBean(String name); / / get the bean instance, according to the bean name and whether the bean is 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 bean instance Class type @nullable Class<? > getType(String name) throws NoSuchBeanDefinitionException; String[] getAliases(String name); // Get the alias of the bean. }Copy the code

1.2. Application Scenarios

Get beans (byName or byType) from the Ioc container

Retrieves whether the specified Bean is contained in the Ioc container

Determine whether the Bean is a singleton

Second, the FactoryBean

It is a Bean first, but not just a Bean. It is a factory Bean that produces or decorates object generation, similar to the Factory and decorator patterns in design patterns. It can produce an object when needed, and not just itself, it can return an instance of any Bean.

2.1, the source code

Public interface FactoryBean<T> {// Get bean from factory @Nullable T getObject() throws Exception; @nullable Class<? > getObjectType(); Default Boolean isSingleton() {return true; }}Copy the code

As you can see from the interface it defines, a FactoryBean represents the responsibilities of a factory. That is, if A Bean A implements the FactoryBean interface, then A becomes A factory. The name of A is actually the object returned by the factory call to getObject(), not A itself. If you want to get an instance of factory A itself, you need to prefix the name with an am&.

GetObject (‘name’) returns the instance in the factory

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

In general, beans don’t have to implement the factory pattern themselves; the Spring container acts as the factory; But in rare cases, the beans in the container are factories themselves, producing other bean instances. Other bean instances produced by the factory bean are no longer produced by the Spring container, so class elements are no longer required, unlike normal bean configurations.

2.2, the sample

Start by defining a Bean that implements the FactoryBean interface

@Component public class MyBean implements FactoryBean { private String message; Public MyBean() {this.message = "initialize instance by constructor "; } @override public Object getObject() throws Exception {// It is not necessary to return an instance of MyBean itself; it can be any other Object. // Return new Student()... Return new MyBean(" create instance by factoryBean.getobject () "); } @Override public Class<? > getObjectType() { return MyBean.class; } public String getMessage() { return message; }}Copy the code

MyBean implements two methods of the FactoryBean interface. GetObject () returns an instance of any object. Here the test returns MyBean itself and assigns a value to the Message field before returning. We also assign a value to message in the constructor. The test code then gets the Bean instance by name, prints the message content, and then gets the instance by &+ name and prints the Message content.

@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)); }}Copy the code

MyBean1 = initializes the instance with FactoryBean.getobject ()

MyBean2 = Initialize myBean1.equals(myBean2) = false via constructor

2.3 Application Scenarios

So why are there factorybeans? What do they do? One of the most typical uses of FactoryBeans in Spring is to create proxy objects for AOP.

We know that AOP actually means that Spring creates a proxy object at run time, that is, the object is created at run time rather than defined from the start, which fits nicely with the factory method pattern. More graphically, AN AOP proxy object creates a proxy object at run time through Java’s reflection mechanism, with methods woven into the target methods of the proxy object based on business requirements. This object in Spring is ProxyFactoryBean.

So, FactoryBeans give us a more flexible way to instantiate beans, and we can create more complex Bean instances from FactoryBeans.

Third, the difference between

Both of them are factories, but a FactoryBean is essentially a Bean, also managed by the BeanFactory

BeanFactory is the top-level interface of the Spring container, and FactoryBeans are more like user-defined factory interfaces.

conclusion

The difference between BeanFactory and FactoryBean can be confusing, and rote memorization is not enough. It is best to understand it from the source level and in the Spring environment.

Spring series of study notes and interview questions, including Spring interview questions, Spring Cloud interview questions, Spring Boot interview questions, Spring Tutorial notes, Spring Boot tutorial notes, 2020 Java Interview Manual. A total of 1184 pages of PDF documents were organized. To get this 1184-page PDF file of the Spring Family bucket information, please click here.