zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    shell编程之 ()[] {}
    mysql环境搭建
    CSS布局基础——BFC
    Java线程
    chrome developer tool—— 断点调试篇
    JavaScript技巧[转载]
    如何在github中创建演示demo
    rem在响应式布局中的应用
    javascript模块化
    浏览器客户端的数据存储
  • 原文地址:https://www.cnblogs.com/yintingting/p/6185086.html
Copyright © 2011-2022 走看看