or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

auto-configuration.mdconfiguration-properties.mdcustomization.mdindex.mdtesting-support.md

auto-configuration.mddocs/

0

# Auto-Configuration

1

2

The MyBatis Spring Boot Starter provides comprehensive auto-configuration that automatically sets up MyBatis components based on classpath detection and configuration properties. This eliminates the need for manual bean definitions while providing extensive customization options.

3

4

## Capabilities

5

6

### MybatisAutoConfiguration

7

8

Main auto-configuration class that creates and configures essential MyBatis beans.

9

10

```java { .api }

11

/**

12

* Auto-configuration for MyBatis that contributes SqlSessionFactory and SqlSessionTemplate.

13

* Automatically configures mapper scanning when @MapperScan is not used.

14

*/

15

@Configuration(proxyBeanMethods = false)

16

@ConditionalOnClass({SqlSessionFactory.class, SqlSessionFactoryBean.class})

17

@ConditionalOnSingleCandidate(DataSource.class)

18

@EnableConfigurationProperties(MybatisProperties.class)

19

@AutoConfigureAfter({DataSourceAutoConfiguration.class, MybatisLanguageDriverAutoConfiguration.class})

20

public class MybatisAutoConfiguration implements InitializingBean {

21

22

/**

23

* Constructor accepting all required dependencies and customizers

24

*/

25

public MybatisAutoConfiguration(

26

MybatisProperties properties,

27

ObjectProvider<Interceptor[]> interceptorsProvider,

28

ObjectProvider<TypeHandler[]> typeHandlersProvider,

29

ObjectProvider<LanguageDriver[]> languageDriversProvider,

30

ResourceLoader resourceLoader,

31

ObjectProvider<DatabaseIdProvider> databaseIdProvider,

32

ObjectProvider<List<ConfigurationCustomizer>> configurationCustomizersProvider,

33

ObjectProvider<List<SqlSessionFactoryBeanCustomizer>> sqlSessionFactoryBeanCustomizers

34

);

35

36

/**

37

* Creates the main SqlSessionFactory bean with auto-configuration

38

* @param dataSource the DataSource to use

39

* @return configured SqlSessionFactory

40

* @throws Exception if configuration fails

41

*/

42

@Bean

43

@ConditionalOnMissingBean

44

public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception;

45

46

/**

47

* Creates the SqlSessionTemplate bean for database operations

48

* @param sqlSessionFactory the SqlSessionFactory to use

49

* @return configured SqlSessionTemplate

50

*/

51

@Bean

52

@ConditionalOnMissingBean

53

public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory);

54

55

/** Validates configuration after properties are set */

56

@Override

57

public void afterPropertiesSet();

58

}

59

```

60

61

**Key Features:**

62

63

- Automatically creates `SqlSessionFactory` and `SqlSessionTemplate` beans

64

- Applies all registered `ConfigurationCustomizer` instances

65

- Applies all registered `SqlSessionFactoryBeanCustomizer` instances

66

- Configures mapper locations, type aliases, and type handlers from properties

67

- Sets up interceptors and language drivers

68

- Validates configuration file existence when required

69

70

### MybatisLanguageDriverAutoConfiguration

71

72

Auto-configuration for additional MyBatis scripting language drivers.

73

74

```java { .api }

75

/**

76

* Auto-configuration for MyBatis scripting language drivers including

77

* FreeMarker, Velocity, and Thymeleaf support

78

*/

79

@Configuration(proxyBeanMethods = false)

80

@ConditionalOnClass(LanguageDriver.class)

81

public class MybatisLanguageDriverAutoConfiguration {

82

83

private static final String CONFIGURATION_PROPERTY_PREFIX = "mybatis.scripting-language-driver";

84

85

/**

86

* Configuration for legacy FreeMarker language driver (version 1.1.x and under)

87

*/

88

@Configuration(proxyBeanMethods = false)

89

@ConditionalOnClass(FreeMarkerLanguageDriver.class)

90

@ConditionalOnMissingClass("org.mybatis.scripting.freemarker.FreeMarkerLanguageDriverConfig")

91

public static class LegacyFreeMarkerConfiguration {

92

@Bean

93

@ConditionalOnMissingBean

94

FreeMarkerLanguageDriver freeMarkerLanguageDriver();

95

}

96

97

/**

98

* Configuration for FreeMarker language driver (version 1.2.x+)

99

*/

100

@Configuration(proxyBeanMethods = false)

101

@ConditionalOnClass({FreeMarkerLanguageDriver.class, FreeMarkerLanguageDriverConfig.class})

102

public static class FreeMarkerConfiguration {

103

@Bean

104

@ConditionalOnMissingBean

105

FreeMarkerLanguageDriver freeMarkerLanguageDriver(FreeMarkerLanguageDriverConfig config);

106

107

@Bean

108

@ConditionalOnMissingBean

109

@ConfigurationProperties(CONFIGURATION_PROPERTY_PREFIX + ".freemarker")

110

public FreeMarkerLanguageDriverConfig freeMarkerLanguageDriverConfig();

111

}

112

113

/**

114

* Configuration for legacy Velocity language driver (version 2.0 and under)

115

*/

116

@Configuration(proxyBeanMethods = false)

117

@ConditionalOnClass(org.mybatis.scripting.velocity.Driver.class)

118

@ConditionalOnMissingClass("org.mybatis.scripting.velocity.VelocityLanguageDriverConfig")

119

@SuppressWarnings("deprecation")

120

public static class LegacyVelocityConfiguration {

121

@Bean

122

@ConditionalOnMissingBean

123

org.mybatis.scripting.velocity.Driver velocityLanguageDriver();

124

}

125

126

/**

127

* Configuration for Velocity language driver (version 2.1.x+)

128

*/

129

@Configuration(proxyBeanMethods = false)

130

@ConditionalOnClass({VelocityLanguageDriver.class, VelocityLanguageDriverConfig.class})

131

public static class VelocityConfiguration {

132

@Bean

133

@ConditionalOnMissingBean

134

VelocityLanguageDriver velocityLanguageDriver(VelocityLanguageDriverConfig config);

135

136

@Bean

137

@ConditionalOnMissingBean

138

@ConfigurationProperties(CONFIGURATION_PROPERTY_PREFIX + ".velocity")

139

public VelocityLanguageDriverConfig velocityLanguageDriverConfig();

140

}

141

142

/**

143

* Configuration for Thymeleaf language driver

144

*/

145

@Configuration(proxyBeanMethods = false)

146

@ConditionalOnClass(ThymeleafLanguageDriver.class)

147

public static class ThymeleafConfiguration {

148

@Bean

149

@ConditionalOnMissingBean

150

ThymeleafLanguageDriver thymeleafLanguageDriver(ThymeleafLanguageDriverConfig config);

151

152

@Bean

153

@ConditionalOnMissingBean

154

@ConfigurationProperties(CONFIGURATION_PROPERTY_PREFIX + ".thymeleaf")

155

public ThymeleafLanguageDriverConfig thymeleafLanguageDriverConfig();

156

}

157

}

158

```

159

160

### Automatic Mapper Scanning

161

162

The auto-configuration includes automatic mapper discovery and registration.

163

164

```java { .api }

165

/**

166

* Automatic mapper scanner that registers all @Mapper annotated interfaces

167

* when no explicit mapper configuration is provided

168

*/

169

public static class AutoConfiguredMapperScannerRegistrar

170

implements BeanFactoryAware, EnvironmentAware, ImportBeanDefinitionRegistrar {

171

172

/**

173

* Registers mapper scanner configuration when auto-configuration packages are available

174

*/

175

@Override

176

public void registerBeanDefinitions(

177

AnnotationMetadata importingClassMetadata,

178

BeanDefinitionRegistry registry

179

);

180

181

@Override

182

public void setBeanFactory(BeanFactory beanFactory);

183

184

@Override

185

public void setEnvironment(Environment environment);

186

}

187

188

/**

189

* Configuration that triggers automatic mapper scanning when no explicit

190

* mapper configuration is found

191

*/

192

@Configuration(proxyBeanMethods = false)

193

@Import(AutoConfiguredMapperScannerRegistrar.class)

194

@ConditionalOnMissingBean({MapperFactoryBean.class, MapperScannerConfigurer.class})

195

public static class MapperScannerRegistrarNotFoundConfiguration implements InitializingBean {

196

@Override

197

public void afterPropertiesSet();

198

}

199

```

200

201

## Auto-Configuration Behavior

202

203

### Conditional Configuration

204

205

The auto-configuration only activates when specific conditions are met:

206

207

```java

208

// Only when MyBatis classes are on classpath

209

@ConditionalOnClass({SqlSessionFactory.class, SqlSessionFactoryBean.class})

210

211

// Only when exactly one DataSource bean exists

212

@ConditionalOnSingleCandidate(DataSource.class)

213

214

// Only creates beans if they don't already exist

215

@ConditionalOnMissingBean

216

217

// Only scans for mappers if no explicit mapper configuration exists

218

@ConditionalOnMissingBean({MapperFactoryBean.class, MapperScannerConfigurer.class})

219

```

220

221

### Configuration Processing Order

222

223

The auto-configuration processes components in this order:

224

225

1. **DataSource Configuration**: Waits for DataSource auto-configuration to complete

226

2. **Language Driver Configuration**: Sets up scripting language drivers first

227

3. **MyBatis Configuration**: Creates core MyBatis beans

228

4. **Mapper Scanning**: Discovers and registers mapper interfaces

229

5. **Customizer Application**: Applies all registered customizers

230

231

### Bean Creation Process

232

233

For SqlSessionFactory creation:

234

235

```java

236

@Bean

237

@ConditionalOnMissingBean

238

public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {

239

SqlSessionFactoryBean factory = new SqlSessionFactoryBean();

240

241

// 1. Set DataSource

242

factory.setDataSource(dataSource);

243

244

// 2. Configure VFS (defaults to SpringBootVFS)

245

if (properties.getConfiguration() == null || properties.getConfiguration().getVfsImpl() == null) {

246

factory.setVfs(SpringBootVFS.class);

247

}

248

249

// 3. Set configuration location if specified

250

if (StringUtils.hasText(this.properties.getConfigLocation())) {

251

factory.setConfigLocation(this.resourceLoader.getResource(this.properties.getConfigLocation()));

252

}

253

254

// 4. Apply core configuration

255

applyConfiguration(factory);

256

257

// 5. Set configuration properties

258

if (this.properties.getConfigurationProperties() != null) {

259

factory.setConfigurationProperties(this.properties.getConfigurationProperties());

260

}

261

262

// 6. Add interceptors

263

if (!ObjectUtils.isEmpty(this.interceptors)) {

264

factory.setPlugins(this.interceptors);

265

}

266

267

// 7. Set database ID provider

268

if (this.databaseIdProvider != null) {

269

factory.setDatabaseIdProvider(this.databaseIdProvider);

270

}

271

272

// 8. Configure type aliases

273

if (StringUtils.hasLength(this.properties.getTypeAliasesPackage())) {

274

factory.setTypeAliasesPackage(this.properties.getTypeAliasesPackage());

275

}

276

277

// 9. Set type handlers

278

if (!ObjectUtils.isEmpty(this.typeHandlers)) {

279

factory.setTypeHandlers(this.typeHandlers);

280

}

281

282

// 10. Configure mapper locations

283

Resource[] mapperLocations = this.properties.resolveMapperLocations();

284

if (!ObjectUtils.isEmpty(mapperLocations)) {

285

factory.setMapperLocations(mapperLocations);

286

}

287

288

// 11. Configure scripting language drivers

289

if (!ObjectUtils.isEmpty(this.languageDrivers)) {

290

factory.setScriptingLanguageDrivers(this.languageDrivers);

291

}

292

293

// 12. Apply SqlSessionFactoryBean customizers

294

applySqlSessionFactoryBeanCustomizers(factory);

295

296

// 13. Build and return SqlSessionFactory

297

return factory.getObject();

298

}

299

```

300

301

## Usage Examples

302

303

### Disabling Auto-Configuration

304

305

```java

306

@SpringBootApplication(exclude = {MybatisAutoConfiguration.class})

307

public class Application {

308

// Auto-configuration disabled - manual configuration required

309

}

310

```

311

312

### Custom Auto-Configuration

313

314

```java

315

@Configuration

316

@AutoConfigureBefore(MybatisAutoConfiguration.class)

317

public class CustomMybatisAutoConfiguration {

318

319

@Bean

320

@Primary

321

public DataSource customDataSource() {

322

// Custom DataSource that will be used by MyBatis auto-configuration

323

return new HikariDataSource();

324

}

325

326

@Bean

327

public Interceptor customInterceptor() {

328

// Custom interceptor that will be automatically registered

329

return new AuditInterceptor();

330

}

331

}

332

```

333

334

### Conditional Bean Replacement

335

336

```java

337

@Configuration

338

public class MyBatisOverrides {

339

340

// This will prevent auto-configuration from creating SqlSessionTemplate

341

@Bean

342

@Primary

343

public SqlSessionTemplate customSqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {

344

return new CustomSqlSessionTemplate(sqlSessionFactory);

345

}

346

}

347

```