BeanFactory和FactoryBean

BeanFactory#

是访问spring的IOC容器核心接口,提供访问spring容器中对象的功能,给IOC容器提供了基础规范。他里面有:

  • BeanDefinition信息,根据这些BeanDefinition,Spring可以创建这些对象。
  • 注册中心,创建的各种Bean都注册在这里
  • Spring的依赖注入功能使用这个BeanFactory接口和子接口来实现。
  • 会加载XML、注解,来配置Bean
  • 核心方法有:各种重载的getBeangetBeanProvider(Class)getType(name)isSingleton(name)/isPrototype(name)isTypeMatch(name, ResolvableType)
  • 实现Bean生命周期回,全套的初始化方法以及它们的标准顺序是:
    • BeanNameAware的setBeanName
    • BeanClassLoaderAware的setBeanClassLoader
    • 实现BeanFactoryAware的setBeanFactory
    • EnvironmentAware的setEnvironment
    • EmbeddedValueResolverAware的setEmbeddedValueResolver
    • ResourceLoaderAware的setResourceLoader (仅适用于应用程序上下文中运行时)
    • ApplicationEventPublisherAware的setApplicationEventPublisher (仅适用于应用程序上下文中运行时)
    • MessageSourceAware的setMessageSource (仅适用于应用程序上下文中运行时)
    • 了ApplicationContextAware的setApplicationContext (仅适用于应用程序上下文中运行时)
    • ServletContextAware的setServletContext (仅适用于Web应用程序上下文中运行时)
    • postProcessBeforeInitialization BeanPostProcessor的方法的InitializingBean的afterPropertiesSet自定义的初始化方法定义
    • postProcessAfterInitialization BeanPostProcessor的方法
  • 在一个bean工厂的关闭,下列生命周期方法适用于:
  • posProcessBeforeDestruction DestructionAwareBeanPostProcessors的方法
  • DisposableBean的destroy方法

BeanFactory的子接口ListableBeanFactory#

是BeanFactory的一个拓展,可以枚举所有的bean实例,所以是listable

下面是一堆可以listable的方法,一次可以拿出来一大堆bean的名称或者对象

  • String[] getBeanDefinitionNames();
  • 各种重载的String[] getBeanNamesForType(ResolvableType type);
  • Map getBeansOfType( Class<T> type)
  • Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotationType)

子接口ApplicationContext#

ApplicationContext作为ListableBeanFactory的子接口(还有一大堆别的接口)

1
2
public interface ApplicationContext extends EnvironmentCapable, ListableBeanFactory, HierarchicalBeanFactory,
MessageSource, ApplicationEventPublisher, ResourcePatternResolver {

又有一大堆功能,提供了配置application的功能,还有

  • 工厂方法来访问应用程序组件。 继承自ListableBeanFactory 。
  • 以通用的方式的能力,加载文件资源。 继承了org.springframework.core.io.ResourceLoader接口。
  • 发布事件注册的侦听器的能力。 继承了ApplicationEventPublisher接口。
  • 有能力解决的消息,支持国际化。 继承了MessageSource接口。
  • 继承自父上下文。 在子上下文定义将始终优先。 这意味着,例如,单个父上下文可以被整个web应用程序被使用,而每个servlet有其自己的子上下文无关的任何其他的servlet。
  • 除了标准的org.springframework.beans.factory.BeanFactory生命周期的能力,ApplicationContext实现检测并调用ApplicationContextAware Bean以及ResourceLoaderAware , ApplicationEventPublisherAware和MessageSourceAware。

Spring实现DefaultListableBeanFactory#

BeanFactory,以Factory结尾,表示它是一个工厂类(接口), 它负责生产和管理bean的一个工厂。在Spring中,BeanFactory是IOC容器的核心接口,它的职责包括:实例化、定位、配置应用程序中的对象及建立这些对象间的依赖。

BeanFactory只是个接口,并不是IOC容器的具体实现,但是Spring容器给出了很多种实现,如 DefaultListableBeanFactory、XmlBeanFactory、ApplicationContext等,其中****XmlBeanFactory就是常用的一个,该实现将以XML方式描述组成应用的对象及对象间的依赖关系。XmlBeanFactory类将持有此XML配置元数据,并用它来构建一个完全可配置的系统或应用。

都是附加了某种功能的实现。 它为其他具体的IOC容器提供了最基本的规范,例如DefaultListableBeanFactory,XmlBeanFactory,ApplicationContext 等具体的容器都是实现了BeanFactory,再在其基础之上附加了其他的功能。

BeanFactory和ApplicationContext就是spring框架的两个IOC容器,现在一般使用ApplicationnContext,其不但包含了BeanFactory的作用,同时还进行更多的扩展。

FactoryBean#

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

它们隐藏了实例化一些复杂Bean的细节,给上层应用带来了便利。从Spring3.0开始,FactoryBean开始支持泛型,即接口声明改为FactoryBean<T>的形式。

以Bean结尾,表示它是一个Bean,不同于普通Bean的是:它是实现了FactoryBean<T>接口的Bean,根据该Bean的ID从BeanFactory中获取的实际上是FactoryBean的getObject()返回的对象,而不是FactoryBean本身,如果要获取FactoryBean对象,请在id前面加一个&符号来获取。

例如自己实现一个FactoryBean,功能:用来代理一个对象,对该对象的所有方法做一个拦截,在调用前后都输出一行LOG,模仿ProxyFactoryBean的功能

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/**
* 代理一个类,拦截该类的所有方法,在方法的调用前后进行日志的输出
*/
public class MyFactoryBean implements FactoryBean<Object>, InitializingBean, DisposableBean {

private static final Logger logger = LoggerFactory.getLogger(MyFactoryBean.class);
private String interfaceName;
private Object target;
private Object proxyObj;
@Override
public void destroy() throws Exception {
logger.debug("destroy......");
}
@Override
public void afterPropertiesSet() throws Exception {
proxyObj = Proxy.newProxyInstance(
this.getClass().getClassLoader(),
new Class[] { Class.forName(interfaceName) },
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
logger.debug("invoke method......" + method.getName());
logger.debug("invoke method before......" + System.currentTimeMillis());
Object result = method.invoke(target, args);
logger.debug("invoke method after......" + System.currentTimeMillis());
return result; }
});
logger.debug("afterPropertiesSet......");
}

@Override
public Object getObject() throws Exception {
logger.debug("getObject......");
return proxyObj;
}

@Override
public Class<?> getObjectType() {
return proxyObj == null ? Object.class : proxyObj.getClass();
}

@Override
public boolean isSingleton() {
return true;
}

public String getInterfaceName() {
return interfaceName;
}

public void setInterfaceName(String interfaceName) {
this.interfaceName = interfaceName;
}

public Object getTarget() {
return target;
}

public void setTarget(Object target) {
this.target = target;
}

public Object getProxyObj() {
return proxyObj;
}

public void setProxyObj(Object proxyObj) {
this.proxyObj = proxyObj;
}

}
1
2
3
4
5
6
7
8
public static void testFactoryBean(ConfigurableApplicationContext context){
Car car = (Car) context.getBean(Car.class);
System.out.println(car.toString());
// 这里拿出来的才是CarFactoryBean
System.out.println(context.getBean("&carFactoryBean").hashCode());
// 这里拿出来的是Car
System.out.println(context.getBean("carFactoryBean").getClass());
}

典型案例—mybatis的SqlSessionFactoryBean#

使用来创建SqlSessionFactory对象的一个FactoryBean,如果没有他直接去创建DefaultSqlSessionFactory,里面需要依赖一个Configuration,这个里面又依赖org.apache.ibatis.mapping.EnvironmentEnvironment里面才有DataSourceTransactionFactory,这是一个很繁琐的链式依赖。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
// 便捷创建SqlSessionFactory对象
public class SqlSessionFactoryBean
implements FactoryBean<SqlSessionFactory>, InitializingBean, ApplicationListener<ApplicationEvent> {

private static final Logger LOGGER = LoggerFactory.getLogger(SqlSessionFactoryBean.class);

private static final ResourcePatternResolver RESOURCE_PATTERN_RESOLVER = new PathMatchingResourcePatternResolver();
private static final MetadataReaderFactory METADATA_READER_FACTORY = new CachingMetadataReaderFactory();

private Resource configLocation;

private Configuration configuration;

private Resource[] mapperLocations;

private DataSource dataSource;

private TransactionFactory transactionFactory;

private Properties configurationProperties;

private SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();

private SqlSessionFactory sqlSessionFactory;

// EnvironmentAware requires spring 3.1
private String environment = SqlSessionFactoryBean.class.getSimpleName();

private boolean failFast;

private Interceptor[] plugins;

private TypeHandler<?>[] typeHandlers;

private String typeHandlersPackage;

@SuppressWarnings("rawtypes")
private Class<? extends TypeHandler> defaultEnumTypeHandler;

private Class<?>[] typeAliases;

private String typeAliasesPackage;

private Class<?> typeAliasesSuperType;

private LanguageDriver[] scriptingLanguageDrivers;

private Class<? extends LanguageDriver> defaultScriptingLanguageDriver;

// issue #19. No default provider.
private DatabaseIdProvider databaseIdProvider;

private Class<? extends VFS> vfs;

private Cache cache;

private ObjectFactory objectFactory;

private ObjectWrapperFactory objectWrapperFactory;


/**
* 在spring的context刷新完毕的时候触发
*/
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (failFast && event instanceof ContextRefreshedEvent) {
// fail-fast -> check all statements are completed
this.sqlSessionFactory.getConfiguration().getMappedStatementNames();
}
}

// 扫描包
private Set<Class<?>> scanClasses(String packagePatterns, Class<?> assignableType) throws IOException {
Set<Class<?>> classes = new HashSet<>();
String[] packagePatternArray = tokenizeToStringArray(packagePatterns,
ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
for (String packagePattern : packagePatternArray) {
Resource[] resources = RESOURCE_PATTERN_RESOLVER.getResources(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
+ ClassUtils.convertClassNameToResourcePath(packagePattern) + "/**/*.class");
for (Resource resource : resources) {
try {
ClassMetadata classMetadata = METADATA_READER_FACTORY.getMetadataReader(resource).getClassMetadata();
Class<?> clazz = Resources.classForName(classMetadata.getClassName());
if (assignableType == null || assignableType.isAssignableFrom(clazz)) {
classes.add(clazz);
}
} catch (Throwable e) {
LOGGER.warn(() -> "Cannot load the '" + resource + "'. Cause by " + e.toString());
}
}
}
return classes;
}



/**
核心方法,创建一个SqlSessionFactory
* Build a {@code SqlSessionFactory} instance.
*
* The default implementation uses the standard MyBatis {@code XMLConfigBuilder} API to build a
* {@code SqlSessionFactory} instance based on a Reader. Since 1.3.0, it can be specified a {@link Configuration}
* instance directly(without config file).
*
* @return SqlSessionFactory
* @throws Exception
* if configuration is failed
*/
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 + "'");
});
}

targetConfiguration.setDefaultEnumTypeHandler(defaultEnumTypeHandler);

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);

if (this.databaseIdProvider != null) {// fix #64 set databaseId before parse mapper xmls
try {
targetConfiguration.setDatabaseId(this.databaseIdProvider.getDatabaseId(this.dataSource));
} catch (SQLException e) {
throw new NestedIOException("Failed getting a databaseId", e);
}
}

Optional.ofNullable(this.cache).ifPresent(targetConfiguration::addCache);

if (xmlConfigBuilder != null) {
try {
xmlConfigBuilder.parse();
LOGGER.debug(() -> "Parsed configuration file: '" + this.configLocation + "'");
} catch (Exception ex) {
throw new NestedIOException("Failed to parse config resource: " + this.configLocation, ex);
} finally {
ErrorContext.instance().reset();
}
}

targetConfiguration.setEnvironment(new Environment(this.environment,
this.transactionFactory == null ? new SpringManagedTransactionFactory() : this.transactionFactory,
this.dataSource));

if (this.mapperLocations != null) {
if (this.mapperLocations.length == 0) {
LOGGER.warn(() -> "Property 'mapperLocations' was specified but matching resources are not found.");
} else {
for (Resource mapperLocation : this.mapperLocations) {
if (mapperLocation == null) {
continue;
}
try {
XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(),
targetConfiguration, mapperLocation.toString(), targetConfiguration.getSqlFragments());
xmlMapperBuilder.parse();
} catch (Exception e) {
throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", e);
} finally {
ErrorContext.instance().reset();
}
LOGGER.debug(() -> "Parsed mapper file: '" + mapperLocation + "'");
}
}
} else {
LOGGER.debug(() -> "Property 'mapperLocations' was not specified.");
}

return this.sqlSessionFactoryBuilder.build(targetConfiguration);
}


// 下面都是一堆设置sqlSessionFactory属性的set方法,类似与<bean>的各个属性

/**
* Sets the ObjectFactory.
*
* @since 1.1.2
* @param objectFactory
* a custom ObjectFactory
*/
public void setObjectFactory(ObjectFactory objectFactory) {
this.objectFactory = objectFactory;
}

/**
* Sets the ObjectWrapperFactory.
*
* @since 1.1.2
* @param objectWrapperFactory
* a specified ObjectWrapperFactory
*/
public void setObjectWrapperFactory(ObjectWrapperFactory objectWrapperFactory) {
this.objectWrapperFactory = objectWrapperFactory;
}

/**
* Gets the DatabaseIdProvider
*
* @since 1.1.0
* @return a specified DatabaseIdProvider
*/
public DatabaseIdProvider getDatabaseIdProvider() {
return databaseIdProvider;
}

/**
* Sets the DatabaseIdProvider. As of version 1.2.2 this variable is not initialized by default.
*
* @since 1.1.0
* @param databaseIdProvider
* a DatabaseIdProvider
*/
public void setDatabaseIdProvider(DatabaseIdProvider databaseIdProvider) {
this.databaseIdProvider = databaseIdProvider;
}

/**
* Gets the VFS.
*
* @return a specified VFS
*/
public Class<? extends VFS> getVfs() {
return this.vfs;
}

/**
* Sets the VFS.
*
* @param vfs
* a VFS
*/
public void setVfs(Class<? extends VFS> vfs) {
this.vfs = vfs;
}

/**
* Gets the Cache.
*
* @return a specified Cache
*/
public Cache getCache() {
return this.cache;
}

/**
* Sets the Cache.
*
* @param cache
* a Cache
*/
public void setCache(Cache cache) {
this.cache = cache;
}

/**
* Mybatis plugin list.
*
* @since 1.0.1
*
* @param plugins
* list of plugins
*
*/
public void setPlugins(Interceptor... plugins) {
this.plugins = plugins;
}

/**
* Packages to search for type aliases.
*
* <p>
* Since 2.0.1, allow to specify a wildcard such as {@code com.example.*.model}.
*
* @since 1.0.1
*
* @param typeAliasesPackage
* package to scan for domain objects
*
*/
public void setTypeAliasesPackage(String typeAliasesPackage) {
this.typeAliasesPackage = typeAliasesPackage;
}

/**
* Super class which domain objects have to extend to have a type alias created. No effect if there is no package to
* scan configured.
*
* @since 1.1.2
*
* @param typeAliasesSuperType
* super class for domain objects
*
*/
public void setTypeAliasesSuperType(Class<?> typeAliasesSuperType) {
this.typeAliasesSuperType = typeAliasesSuperType;
}

/**
* Packages to search for type handlers.
*
* <p>
* Since 2.0.1, allow to specify a wildcard such as {@code com.example.*.typehandler}.
*
* @since 1.0.1
*
* @param typeHandlersPackage
* package to scan for type handlers
*
*/
public void setTypeHandlersPackage(String typeHandlersPackage) {
this.typeHandlersPackage = typeHandlersPackage;
}

/**
* Set type handlers. They must be annotated with {@code MappedTypes} and optionally with {@code MappedJdbcTypes}
*
* @since 1.0.1
*
* @param typeHandlers
* Type handler list
*/
public void setTypeHandlers(TypeHandler<?>... typeHandlers) {
this.typeHandlers = typeHandlers;
}

/**
* Set the default type handler class for enum.
*
* @since 2.0.5
* @param defaultEnumTypeHandler
* The default type handler class for enum
*/
public void setDefaultEnumTypeHandler(
@SuppressWarnings("rawtypes") Class<? extends TypeHandler> defaultEnumTypeHandler) {
this.defaultEnumTypeHandler = defaultEnumTypeHandler;
}

/**
* List of type aliases to register. They can be annotated with {@code Alias}
*
* @since 1.0.1
*
* @param typeAliases
* Type aliases list
*/
public void setTypeAliases(Class<?>... typeAliases) {
this.typeAliases = typeAliases;
}

/**
* If true, a final check is done on Configuration to assure that all mapped statements are fully loaded and there is
* no one still pending to resolve includes. Defaults to false.
*
* @since 1.0.1
*
* @param failFast
* enable failFast
*/
public void setFailFast(boolean failFast) {
this.failFast = failFast;
}

/**
* Set the location of the MyBatis {@code SqlSessionFactory} config file. A typical value is
* "WEB-INF/mybatis-configuration.xml".
*
* @param configLocation
* a location the MyBatis config file
*/
public void setConfigLocation(Resource configLocation) {
this.configLocation = configLocation;
}

/**
* Set a customized MyBatis configuration.
*
* @param configuration
* MyBatis configuration
* @since 1.3.0
*/
public void setConfiguration(Configuration configuration) {
this.configuration = configuration;
}

/**
* Set locations of MyBatis mapper files that are going to be merged into the {@code SqlSessionFactory} configuration
* at runtime.
*
* This is an alternative to specifying "&lt;sqlmapper&gt;" entries in an MyBatis config file. This property being
* based on Spring's resource abstraction also allows for specifying resource patterns here: e.g.
* "classpath*:sqlmap/*-mapper.xml".
*
* @param mapperLocations
* location of MyBatis mapper files
*/
public void setMapperLocations(Resource... mapperLocations) {
this.mapperLocations = mapperLocations;
}

/**
* Set optional properties to be passed into the SqlSession configuration, as alternative to a
* {@code &lt;properties&gt;} tag in the configuration xml file. This will be used to resolve placeholders in the
* config file.
*
* @param sqlSessionFactoryProperties
* optional properties for the SqlSessionFactory
*/
public void setConfigurationProperties(Properties sqlSessionFactoryProperties) {
this.configurationProperties = sqlSessionFactoryProperties;
}

/**
* Set the JDBC {@code DataSource} that this instance should manage transactions for. The {@code DataSource} should
* match the one used by the {@code SqlSessionFactory}: for example, you could specify the same JNDI DataSource for
* both.
*
* A transactional JDBC {@code Connection} for this {@code DataSource} will be provided to application code accessing
* this {@code DataSource} directly via {@code DataSourceUtils} or {@code DataSourceTransactionManager}.
*
* The {@code DataSource} specified here should be the target {@code DataSource} to manage transactions for, not a
* {@code TransactionAwareDataSourceProxy}. Only data access code may work with
* {@code TransactionAwareDataSourceProxy}, while the transaction manager needs to work on the underlying target
* {@code DataSource}. If there's nevertheless a {@code TransactionAwareDataSourceProxy} passed in, it will be
* unwrapped to extract its target {@code DataSource}.
*
* @param dataSource
* a JDBC {@code DataSource}
*
*/
public void setDataSource(DataSource dataSource) {
if (dataSource instanceof TransactionAwareDataSourceProxy) {
// If we got a TransactionAwareDataSourceProxy, we need to perform
// transactions for its underlying target DataSource, else data
// access code won't see properly exposed transactions (i.e.
// transactions for the target DataSource).
this.dataSource = ((TransactionAwareDataSourceProxy) dataSource).getTargetDataSource();
} else {
this.dataSource = dataSource;
}
}

/**
* Sets the {@code SqlSessionFactoryBuilder} to use when creating the {@code SqlSessionFactory}.
*
* This is mainly meant for testing so that mock SqlSessionFactory classes can be injected. By default,
* {@code SqlSessionFactoryBuilder} creates {@code DefaultSqlSessionFactory} instances.
*
* @param sqlSessionFactoryBuilder
* a SqlSessionFactoryBuilder
*
*/
public void setSqlSessionFactoryBuilder(SqlSessionFactoryBuilder sqlSessionFactoryBuilder) {
this.sqlSessionFactoryBuilder = sqlSessionFactoryBuilder;
}

/**
* Set the MyBatis TransactionFactory to use. Default is {@code SpringManagedTransactionFactory}
*
* The default {@code SpringManagedTransactionFactory} should be appropriate for all cases: be it Spring transaction
* management, EJB CMT or plain JTA. If there is no active transaction, SqlSession operations will execute SQL
* statements non-transactionally.
*
* <b>It is strongly recommended to use the default {@code TransactionFactory}.</b> If not used, any attempt at
* getting an SqlSession through Spring's MyBatis framework will throw an exception if a transaction is active.
*
* @see SpringManagedTransactionFactory
* @param transactionFactory
* the MyBatis TransactionFactory
*/
public void setTransactionFactory(TransactionFactory transactionFactory) {
this.transactionFactory = transactionFactory;
}

/**
* <b>NOTE:</b> This class <em>overrides</em> any {@code Environment} you have set in the MyBatis config file. This is
* used only as a placeholder name. The default value is {@code SqlSessionFactoryBean.class.getSimpleName()}.
*
* @param environment
* the environment name
*/
public void setEnvironment(String environment) {
this.environment = environment;
}

/**
* Set scripting language drivers.
*
* @param scriptingLanguageDrivers
* scripting language drivers
* @since 2.0.2
*/
public void setScriptingLanguageDrivers(LanguageDriver... scriptingLanguageDrivers) {
this.scriptingLanguageDrivers = scriptingLanguageDrivers;
}

/**
* Set a default scripting language driver class.
*
* @param defaultScriptingLanguageDriver
* A default scripting language driver class
* @since 2.0.2
*/
public void setDefaultScriptingLanguageDriver(Class<? extends LanguageDriver> defaultScriptingLanguageDriver) {
this.defaultScriptingLanguageDriver = defaultScriptingLanguageDriver;
}

/**
* {@inheritDoc}
*/
@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();
}


/**
* {@inheritDoc}
*/
@Override
public SqlSessionFactory getObject() throws Exception {
if (this.sqlSessionFactory == null) {
afterPropertiesSet();
}

return this.sqlSessionFactory;
}

/**
* {@inheritDoc}
*/
@Override
public Class<? extends SqlSessionFactory> getObjectType() {
return this.sqlSessionFactory == null ? SqlSessionFactory.class : this.sqlSessionFactory.getClass();
}

/**
* {@inheritDoc}
*/
@Override
public boolean isSingleton() {
return true;
}



}

https://www.cnblogs.com/aspirant/p/9082858.html