spring-FactoryBean

 

package org.springframework.beans.factory;

import org.springframework.lang.Nullable;

public interface FactoryBean<T> {
    @Nullable
    T getObject() throws Exception;

    @Nullable
    Class<?> getObjectType();

    default boolean isSingleton() {
        return true;
    }
}

 

如果你的类实现了FactoryBean,那么spring IOC容器中存在两个对象

一个是getObject方法返回的对象(当前类的名字首字母小写)

一个是当前对象(怎么存的? &+当前类的名字首字母小写)

package com.test2;

public class TestMyFactoryBean {

    public void test(){
        System.out.println("test TestMyFactoryBean");

    }
}
package com.test2;

import org.springframework.beans.factory.FactoryBean;
import org.springframework.stereotype.Component;

@Component
public class MyFactoryBean implements FactoryBean {

    public void test(){
        System.out.println("test MyFactoryBean");
    }
    public Object getObject() throws Exception {
        return new TestMyFactoryBean();
    }

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

    public boolean isSingleton() {
        return true;
    }
}
package com.test2;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MyTest {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context =
                new AnnotationConfigApplicationContext(MyFactoryBean.class);
        System.out.println(context.getBean(MyFactoryBean.class));
        System.out.println(context.getBean("myFactoryBean"));
        System.out.println(context.getBean(TestMyFactoryBean.class));
      System.out.println(context.getBean("&myFactoryBean"));
} }

输出结果:

com.test2.MyFactoryBean@131276c2
com.test2.TestMyFactoryBean@26aa12dd
com.test2.TestMyFactoryBean@26aa12dd
com.test2.MyFactoryBean@131276c2

 

什么时候用呢?

一个类的依赖关系比较复杂,可以通过FactoryBean类向外部提供一个简单的方式让人快速获取到。

比如mybatis中的:

public class SqlSessionFactoryBean implements FactoryBean<SqlSessionFactory>, InitializingBean, ApplicationListener<ApplicationEvent> {
public SqlSessionFactory getObject() throws Exception {
if (this.sqlSessionFactory == null) {
this.afterPropertiesSet();
}

return this.sqlSessionFactory;
}

 

posted @ 2016-12-15 22:21  Emyin  阅读(152)  评论(0编辑  收藏  举报