The difference between spring and face questions --- beanFactory of factoryBean

    BeanFactory is the interface to provide the most basic form of container IOC, the IOC to achieve specific container provides specifications

    FactoryBean also interface, providing a more flexible way for the IOC container Implementation Bean, FactoryBean on the basis of the IOC container to achieve Bean, plus a simple factory pattern and decorative patterns, we can flexibly configure the getObject () method . In fact, there are many FactoryBean implementation class in the Spring source code.

Difference: BeanFactory is a Factory, is the IOC container or object factories, FactoryBean a Bean. In Spring, all Bean are to be managed by the BeanFactory (ie IOC container) . But FactoryBean concerned, this is not a simple Bean Bean, but a generation capable of producing or modifying objects Bean plant, similar to its implementation and design model of the factory model and modified mode 

  1、 BeanFactory

BeanFactory, ending Factory, indicating that it is a factory class ( Interface ), which is responsible for the production and management of a factory bean. In Spring, the BeanFactory core interface is IOC containers , Its responsibilities include : instantiating or configuration application objects and the dependencies between those objects . BeanFactory only interfaces, not the specific realization IOC containers, but Spring container gives many implementations, such as DefaultListableBeanFactory, XmlBeanFactory, ApplicationContext the like, which is commonly used in a XmlBeanFactory, to achieve the objects described in XML and application dependencies between objects.

package org.springframework.beans.factory;

import org.springframework.beans.BeansException;
import org.springframework.core.ResolvableType;
import org.springframework.lang.Nullable;

public interface BeanFactory {

    /**
    用于区分factoryBean和bean,后面会讲到
*/ String FACTORY_BEAN_PREFIX = "&"; /** 返回byName返回bean的实例*/ Object getBean(String name) throws BeansException; <T> T getBean(String name, 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; /** * Return a provider for the specified bean, allowing for lazy on-demand retrieval * of instances, including availability and uniqueness options. * @param requiredType type the bean must match; can be an interface or superclass * @return a corresponding provider handle * @since 5.1 * @see #getBeanProvider(ResolvableType) */ <T> ObjectProvider <T> getBeanProvider (Class <T> requiredType); <T> ObjectProvider <T> getBeanProvider (ResolvableType requiredType); / **      determined whether the plant contains the bean definitions given name, if it returns to true * / Boolean containsBean (String name); / ** determines whether singleton bean * / Boolean isSingleton (String name) throws NoSuchBeanDefinitionException will; / **     determines whether a plurality Example bean * / Boolean isPrototype (String name) throws NoSuchBeanDefinitionException will; / * * check the type to have bean given name matches the specified. * / Boolean isTypeMatch (String name, ResolvableType typeToMatch)      throws NoSuchBeanDefinitionException; boolean isTypeMatch (<?> String name, Class typeToMatch) throws NoSuchBeanDefinitionException; / **     returned to the bean's Class given name, if the specified bean instance is not found, excluded * / @Nullable Class getType (<?> name String) throws NoSuchBeanDefinitionException will; / **     returns the names of all the given bean aliases  * / String [] getAliases (String name); }

 

  2、FactoryBean

  

In general, Spring reflection by using <bean> attribute specifies the class of the Bean class instance, under certain circumstances, Bean instantiation process is complex, if the conventional manner, it is necessary to provide a large amount in the <bean> in the configuration information. Flexibility of arrangement is limited, when the coding method employed may get a simple solution. Spring factory class provides the interface for this org.springframework.bean.factory.FactoryBean a user can instantiate Bean by logic implementing this interface customization. FactoryBean interfaces for the Spring Framework occupy an important position, Spring provides its own implementation of more than 70 FactoryBean . They hide the details of some of the examples of complex Bean, to the upper application is made easier. From Spring3.0 start, FactoryBean began to support generic, namely the interface declaration instead FactoryBean <T> form

Ending Bean, indicating that it is a Bean, Bean is different from the ordinary: it is realized FactoryBean <T> Bean interface, based on the ID obtained from the Bean is actually the FactoryBean BeanFactory getObject () object returned instead FactoryBean itself, if you want to get FactoryBean object, add an ampersand in front of the id to get.

  For example: I defined a class Car {Name, Color ... etc. properties}, I need to initialize spring containers

  

public class Car {
    private String Name;
    private String color;

    public String getName() {
        return Name;
    }

    public void setName(String name) {
        Name = name;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    @Override
    public String toString() {
        return "Car{" +
                "Name='" + Name + '\'' +
                ", color='" + color + '\'' +
                '}';
    }
}

 

    Method a: configure its spring by way of the xml.

    Method two: CarProxy define a class that implements the interface factoryBean.

public class CarProxy implements FactoryBean<Car> {

    private String msg;

    private Car car;
//重写getObject方法,返回car实例 @Override
public Car getObject() throws Exception { Car car = new Car(); String[] magArr = msg.split(","); car.setName(magArr[0]); car.setColor(magArr[1]); this.car = car; return car; } @Override public Class<?> getObjectType() { return this.getClass()==null?car.getClass():this.getClass(); } public void setMsg(String msg) { this.msg = msg; } }

xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="car" class="cn.cg.beanFactory.CarProxy">
        <property name="msg" value="法拉利,红色" />

    </bean>
</beans>

test:

  

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class MyTest {
    @Autowired
    private ApplicationContext ac;
    @Test
    public void fun1(){
        //car
        Car car = (Car) ac.getBean("car");
        System.out.println(car);
    }
}

console:

  

Car {Name = 'Ferrari', color = 'Red'}

Careful observation: "car" ----> cn.cg.beanFactory.CarProxy

Reason ac.getBean ( "car"); objects acquired should be CarProxy objects, but I convert the object became a Car object, and successfully calling the toString () method they override that ???

Because when we getBean, spring FactoryBean of classes that implement the interface to achieve a special treatment

When you call getBean ( "car"), Spring by found CarFactoryBean achieved FactoryBean interface reflection ,

Then the Spring container calls the interface method CarFactoryBean # getObject () method returns. If you wish to obtain an instance of CarFactoryBean,

With "&" prefix is ​​required before beanName displayed when using the getBean (beanName) Method: as getBean ( "& car");  

Why should spring design

one of the reasons:

  For example, we need to integrate spring mybatis, in the absence of the mybatis-spring (spring-the mybatis MyBatis will help you to seamlessly integrate the code into the Spring),

  We need to mybatis core classes SqlSessionFactory injected into the container spring, then think to use the two most common ways

  (1) notes, can mybatis is an independent project. Nothing to do with spring, so Pass !!!!

  (2) xml, sqlSessionFacory need to inject a lot of dependencies, inconvenient maintenance

  So you can choose a proxy class to handle sqlSessionFacory, which is what we use in integrated spring + mybatis of SqlSessionFactoryBean

Reference: https://www.cnblogs.com/aspirant/p/9082858.html

 

Guess you like

Origin www.cnblogs.com/cg961107/p/11261767.html