• 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;
    }
  • 相关阅读:
    第04组 Alpha冲刺 总结
    第04组 Alpha冲刺 (6/6)
    软工实践个人总结
    第09组 每周小结 (3/3)
    第09组 每周小结 (2/3)
    第09组 每周小结 (1/3)
    第09组 Beta冲刺 总结
    第09组 Beta冲刺 (5/5)
    第09组 Beta冲刺 (4/5)
    第09组 Beta冲刺 (3/5)
  • 原文地址:https://www.cnblogs.com/yintingting/p/6185086.html
Copyright © 2020-2023  润新知