Spring中FactoryBean的使用 - Go语言中文社区

Spring中FactoryBean的使用


       本文主要介绍什么是FactoryBean技术?为什么使用FactoryBean?使用FactoryBean的好处?目前优秀的框架有哪些用到了FactoryBean?如果想要了解FactoryBean的源码请移步:Spring中FactoryBean源码分析(最详细)

1. FactoryBean的介绍:

       FactoryBean从字面意思上理解是工厂bean,他可以生成某一个类型Bean实例,它最大的一个作用是:可以让我们自定义Bean的创建过程。

       一般情况下,Spring通过反射机制利用<bean>的class属性指定实现类实例化Bean,在某些情况下,实例化Bean过程比较复杂,如果按照传统的方式,则需要在<bean>中提供大量的配置信息。配置方式的灵活性是受限的,这时采用编码的方式可能会得到一个简单的方案。Spring为此提供了一个org.springframework.bean.factory.FactoryBean的工厂类接口,用户可以通过实现该接口定制实例化Bean的逻辑。FactoryBean接口对于Spring框架来说占用重要的地位,Spring自身就提供了70多个FactoryBean的实现。它们隐藏了实例化一些复杂Bean的细节,给上层应用带来了便利。

      我们先来看一下FactoryBean这个接口:

public interface FactoryBean<T> {

	String OBJECT_TYPE_ATTRIBUTE = "factoryBeanObjectType";

    //返回对象实例
	@Nullable
	T getObject() throws Exception;

    //bean的Class类型
	@Nullable
	Class<?> getObjectType();

    //true是单例,false是非单例,可以看出默认为单例的
	default boolean isSingleton() {
		return true;
	}

}

      可以看到FactoryBean是一个泛型类,而且只有三个方法,如果你想要的类是一个单例,那么只需要实现两个方法就可以了,getObject方法返回一个对象的实例,getObjectType方法返回对象的Class类型。

      看下面一个例子:

package com.luban.factoryBean;
@Component("schoolFactory")
public class SchoolFactoryBean implements FactoryBean {
	@Override
	public Object getObject() throws Exception {
		return new School();
	}
	@Override
	public Class<?> getObjectType() {
		return School.class;
	}
	@Override
	public boolean isSingleton() {
		return true;
	}
}
@Configuration
@ComponentScan("com.luban.factoryBean")
public class Config {	
}
public class Test {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext contextnew = new AnnotationConfigApplicationContext(Config.class);
		School school = (School) contextnew.getBean("schoolFactory");
		System.out.println(school);
		SchoolFactoryBean schoolFactoryBean = (SchoolFactoryBean) contextnew.getBean("&schoolFactory");
		System.out.println(schoolFactoryBean);
	}
}
打印结果:
com.luban.School@3834d63f
com.luban.factoryBean.SchoolFactoryBean@1ae369b7

       可以看到我们在SchoolFactoryBean类上面标注了schoolFactory的名称,当我们去容器中取schoolFactory的时候,他是School类型的了,从这可以看出在获取FactoryBean的时候,其实返回的是通过getObject拿到的值,如果想要获取SchoolFactoryBean类本身,需要加上在前面加上“&”符号才能获取SchoolFactoryBean本身。

       现在对于FactoryBean有了基本的认识,可能会觉得这样做毫无意思啊,为什么要使用FactoryBean包裹一层呢,这样不就麻烦了吗?

2. FactoryBean的作用:

       关于为什么使用FactoryBean,下面给出几点原因:

        一:如果实例化一个Bean的过程比较复杂,如果按照传统的方式,则需要在<bean>中提供大量的配置信息,而这些信息还是我们不需要去关注的,我们只想要创建一个bean,不想知道这个bean是经过多么复杂的流程创建出来的,这个我们不关心,这是就可以使用FactoryBean来把一些配置信息、依赖项进行封装在内部,这样就可以很简单的实例化一个bean。

        二:和第三方框架的整合,首先在第三方框架内部是不会出现像@Component这样的注解(因为如果使用了@Component注解,就依赖了Spring),在和Spring进行整合的时候,就需要将第三方的类以注解或者是XML的形式放到Spring容器中去,往往第三方类都有一个非常重要的类,我们只需要将这个类注入到Spring就可以了,不过这个类想要正常工作可能会依赖其他的,(为什么需要依赖其他的类,想一想单一性原则),所以我们在Spring中想注入这个类,就需要先知道它依赖的其他类,可以其他类还会有依赖,这样做就太麻烦了,所以第三方框架可以写一个FactoryBean类,提供一个简单和Spring进行整合的入口(为什么是第三方框架自己写,毕竟框架是他写的,他比我们清楚这个),我们只需要将这个FactoryBean类以注解或XML的格式放到容器就可以了。

3. MyBatis对FactoryBean的使用:

        对于MyBatis熟悉的同学都知道,MyBatis在和Spring进行整合的时候需要在XML中配置SqlSessionFactory,

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
  <property name="mapperLocations" value="classpath*:sample/config/mappers/**/*.xml" />
</bean>

       或者是你使用的是SpringBoot项目整合MyBatis你没有看到你自己有写SqlSessionFactory,但是你不写有人帮你写了,在MybatisAutoConfiguration类中又这么一个@bean注解:

@Bean
  @ConditionalOnMissingBean
  public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
    SqlSessionFactoryBean factory = new SqlSessionFactoryBean();//使用SqlSessionFactoryBean来创建的SqlSessionFactory
    factory.setDataSource(dataSource);
    factory.setVfs(SpringBootVFS.class);
    if (StringUtils.hasText(this.properties.getConfigLocation())) {
      factory.setConfigLocation(this.resourceLoader.getResource(this.properties.getConfigLocation()));
    }
    applyConfiguration(factory);
    if (this.properties.getConfigurationProperties() != null) {
      factory.setConfigurationProperties(this.properties.getConfigurationProperties());
    }
    if (!ObjectUtils.isEmpty(this.interceptors)) {
      factory.setPlugins(this.interceptors);
    }
    if (this.databaseIdProvider != null) {
      factory.setDatabaseIdProvider(this.databaseIdProvider);
    }
    if (StringUtils.hasLength(this.properties.getTypeAliasesPackage())) {
      factory.setTypeAliasesPackage(this.properties.getTypeAliasesPackage());
    }
    if (this.properties.getTypeAliasesSuperType() != null) {
      factory.setTypeAliasesSuperType(this.properties.getTypeAliasesSuperType());
    }
    if (StringUtils.hasLength(this.properties.getTypeHandlersPackage())) {
      factory.setTypeHandlersPackage(this.properties.getTypeHandlersPackage());
    }
    if (!ObjectUtils.isEmpty(this.typeHandlers)) {
      factory.setTypeHandlers(this.typeHandlers);
    }
    if (!ObjectUtils.isEmpty(this.properties.resolveMapperLocations())) {
      factory.setMapperLocations(this.properties.resolveMapperLocations());
    }
    Set<String> factoryPropertyNames = Stream
        .of(new BeanWrapperImpl(SqlSessionFactoryBean.class).getPropertyDescriptors()).map(PropertyDescriptor::getName)
        .collect(Collectors.toSet());
    Class<? extends LanguageDriver> defaultLanguageDriver = this.properties.getDefaultScriptingLanguageDriver();
    if (factoryPropertyNames.contains("scriptingLanguageDrivers") && !ObjectUtils.isEmpty(this.languageDrivers)) {
      // Need to mybatis-spring 2.0.2+
      factory.setScriptingLanguageDrivers(this.languageDrivers);
      if (defaultLanguageDriver == null && this.languageDrivers.length == 1) {
        defaultLanguageDriver = this.languageDrivers[0].getClass();
      }
    }
    if (factoryPropertyNames.contains("defaultScriptingLanguageDriver")) {
      // Need to mybatis-spring 2.0.2+
      factory.setDefaultScriptingLanguageDriver(defaultLanguageDriver);
    }

    return factory.getObject();
  }

      再次简单说明一下,this.properties就是你在application.yaml或者是application.properties中配置的关于MyBatis的信息都会被保存this.properties保存其他。

      我们以SpringBoot整合MyBatis为例进行说明,看下图:

              

      你可以配置关于MyBatis的相关信息,但是你不用每一个环境变量、依赖项都配置,只需要配置你感兴趣的,然后关于其他的配置都会在factory.getObject()中由MyBatis自行去配置。

      那么我们看一下SqlSessionFactoryBean的源码:

public class SqlSessionFactoryBean
    implements FactoryBean<SqlSessionFactory>, InitializingBean, ApplicationListener<ApplicationEvent> {

//已省略无关代码

  @Override
  public SqlSessionFactory getObject() throws Exception {
    if (this.sqlSessionFactory == null) {
      afterPropertiesSet();
    }
    return this.sqlSessionFactory;
  }
   @Override
   public void afterPropertiesSet() throws Exception {
    notNull(dataSource, "Property 'dataSource' is required");
    notNull(sqlSessionFactoryBuilder, "Property 'sqlSessionFactoryBuilder' is required");
    state((configuration == null && configLocation == null) || !(configuration != null && configLocation != null),
        "Property 'configuration' and 'configLocation' can not specified with together");

    this.sqlSessionFactory = buildSqlSessionFactory();
  }

    protected SqlSessionFactory buildSqlSessionFactory() throws Exception {
    final Configuration targetConfiguration;

    XMLConfigBuilder xmlConfigBuilder = null;
    if (this.configuration != null) {
      targetConfiguration = this.configuration;
      if (targetConfiguration.getVariables() == null) {
        targetConfiguration.setVariables(this.configurationProperties);
      } else if (this.configurationProperties != null) {
        targetConfiguration.getVariables().putAll(this.configurationProperties);
      }
    } else if (this.configLocation != null) {
      xmlConfigBuilder = new XMLConfigBuilder(this.configLocation.getInputStream(), null, this.configurationProperties);
      targetConfiguration = xmlConfigBuilder.getConfiguration();
    } else {
      LOGGER.debug(
          () -> "Property 'configuration' or 'configLocation' not specified, using default MyBatis Configuration");
      targetConfiguration = new Configuration();
      Optional.ofNullable(this.configurationProperties).ifPresent(targetConfiguration::setVariables);
    }

    Optional.ofNullable(this.objectFactory).ifPresent(targetConfiguration::setObjectFactory);
    Optional.ofNullable(this.objectWrapperFactory).ifPresent(targetConfiguration::setObjectWrapperFactory);
    Optional.ofNullable(this.vfs).ifPresent(targetConfiguration::setVfsImpl);

    if (hasLength(this.typeAliasesPackage)) {
      scanClasses(this.typeAliasesPackage, this.typeAliasesSuperType).stream()
          .filter(clazz -> !clazz.isAnonymousClass()).filter(clazz -> !clazz.isInterface())
          .filter(clazz -> !clazz.isMemberClass()).forEach(targetConfiguration.getTypeAliasRegistry()::registerAlias);
    }

    if (!isEmpty(this.typeAliases)) {
      Stream.of(this.typeAliases).forEach(typeAlias -> {
        targetConfiguration.getTypeAliasRegistry().registerAlias(typeAlias);
        LOGGER.debug(() -> "Registered type alias: '" + typeAlias + "'");
      });
    }

    if (!isEmpty(this.plugins)) {
      Stream.of(this.plugins).forEach(plugin -> {
        targetConfiguration.addInterceptor(plugin);
        LOGGER.debug(() -> "Registered plugin: '" + plugin + "'");
      });
    }

    if (hasLength(this.typeHandlersPackage)) {
      scanClasses(this.typeHandlersPackage, TypeHandler.class).stream().filter(clazz -> !clazz.isAnonymousClass())
          .filter(clazz -> !clazz.isInterface()).filter(clazz -> !Modifier.isAbstract(clazz.getModifiers()))
          .forEach(targetConfiguration.getTypeHandlerRegistry()::register);
    }

    if (!isEmpty(this.typeHandlers)) {
      Stream.of(this.typeHandlers).forEach(typeHandler -> {
        targetConfiguration.getTypeHandlerRegistry().register(typeHandler);
        LOGGER.debug(() -> "Registered type handler: '" + typeHandler + "'");
      });
    }

    if (!isEmpty(this.scriptingLanguageDrivers)) {
      Stream.of(this.scriptingLanguageDrivers).forEach(languageDriver -> {
        targetConfiguration.getLanguageRegistry().register(languageDriver);
        LOGGER.debug(() -> "Registered scripting language driver: '" + languageDriver + "'");
      });
    }
    Optional.ofNullable(this.defaultScriptingLanguageDriver)
        .ifPresent(targetConfiguration::setDefaultScriptingLanguage);    

    return this.sqlSessionFactoryBuilder.build(targetConfiguration);
  }
}

        这个配置简直是太麻烦了,而现在呢,我们只需要配置我们感兴趣的,其他的交给MyBatis自己写的FactoryBean就可以了,现在我们知道了FactoryBean的重要性了吧。

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/qq_35634181/article/details/104499791
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-03-01 17:37:52
  • 阅读 ( 1698 )
  • 分类:

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢