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;
    }
  • 相关阅读:
    鱼群生长曲线分析
    记住这一刻,学会感恩
    编译boost命令
    ASP之SOAP的发送、接收与处理类[转载]
    在WinForm中使用WebServices来实现软件自动升级(AutoUpdate)(C#)[转载]
    .Net下采用GET/POST/SOAP方式动态调用WebService的简易灵活方法(C#) [轉]Redfox
    使用 HttpWebRequest 类调用 WEB 服务的示例(C#)【转载】
    Log4Net使用指南
    C# post xml using HttpWebRequest/Response
    XmlHttp对象简介[转载]
  • 原文地址:https://www.cnblogs.com/yintingting/p/6185086.html
Copyright © 2011-2022 走看看