The difference between Factorybean and Beanfactory in spring-ioc

        FactoryBean and BeanFactory are both interfaces in spring. From the name, you must think that these two things have some connection, but in fact, these two interfaces really have nothing to do with the name.

(1)BeanFactory

          This interface is the top-level interface of the spring IOC container. You can look at the class diagram.

This interface provides the most basic container methods. Other container classes inherit this interface to expand the corresponding functions. Interested students can go and see

(2)FactoryBean

        This interface is an interface provided by spring for decorating user beans. The decorator pattern is used here. Students who have not studied it can read my other blog post: https://my.oschina.net/u/1169535/blog /757276

        for example

        Entity class:

        

public class C {

    private String attr;


    public String getAttr() {
        return attr;
    }

    public void setAttr(String attr) {
        this.attr = attr;
    }
}

spring xml configuration file

<bean name="c" class="com.chameleon.dao.daoImpl.C">
   <property name="attr" value="ceshi"/>
</bean>

test class

public class MainClient {
    public static void main(String[] args) {
        BeanFactory beanFactory = new ClassPathXmlApplicationContext("META-INF/spring/chameleon-context.xml");
        C c =  (C)beanFactory.getBean("c");
        System.out.println(c.getAttr());
    }
}

Result: ceshi

This is a simple example of spring dependency injection that couldn't be simpler

Now I have an idea, that is, when I get the instance of C, I will notify you to mark it, or count it. What should I do? At this time, you can use factorybean to decorate it, you only need to change the entity class

public class C implements FactoryBean {
    private String attr;
    
    public String getAttr() {
        return attr;
    }

    public void setAttr(String attr) {
        this.attr = attr;
    }

    public Object getObject() throws Exception {
        System.out.println("Decorate");
        C c = new C();
        c.setAttr(attr);
        return c;
    }

    public Class<?> getObjectType() {
        return C.class;
    }

    public boolean isSingleton() {
        return true;
    }
}

run the test

The result is:

decorate
the ceshi

        The specific implementation is that when spring performs dependency injection, it will determine whether the current bean is instanceOf factoryBean. If it belongs, it will execute the getObject method to return the object instance. Students who are interested in the specific details can see the corresponding code.

 

 

        

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325510614&siteId=291194637