Spring Boot Integration Guide: MyBatis, Swagger2, Multi‑Environment Configuration and Advanced Logging
This article explains why to use Spring Boot, how to set up the development environment, and provides step‑by‑step instructions for integrating MyBatis, Swagger2, multi‑environment profiles, and advanced Logback logging, including configuration files, Maven dependencies, code snippets, and testing procedures.
Spring Boot simplifies the initial setup of Spring applications by providing default configurations, eliminating the need for numerous XML files, and is recommended over the traditional SSM stack.
The tutorial starts by creating a Spring Boot 2.0 project using IDEA or by downloading the starter from the official site, ensuring JDK 1.8+ is used.
After generating the project, the application.yml file is edited to replace the traditional .properties format with a more concise YAML structure.
# properties式语法描述
spring.datasource.name = mysql
spring.datasource.url = jdbc:mysql://localhost:3306/db?characterEncoding=utf-8
spring.datasource.username = root
spring.datasource.password = 123
# yml式语法描述
spring:
datasource:
name: mysql
url: jdbc:mysql://localhost:3306/db?characterEncoding=utf-8
username: root
password: 123
type: com.alibaba.druid.pool.DruidDataSource
filters: stat,log4j,wall
maxActive: 20
initialSize: 1
maxWait: 60000
minIdle: 1
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: select count(1) from 'table'
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: false
maxOpenPreparedStatements: -1Key Maven dependencies are added to pom.xml to include Spring Boot starter web, MyBatis starter, MySQL driver, Druid, PageHelper, Fastjson, and Swagger2.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.5.0</version>
</dependency>MyBatis integration includes configuring Druid as the datasource, adding PageHelper for pagination, and setting up the MyBatis Generator plugin for reverse‑engineering DAO, POJO, and mapper XML files.
# pagehelper分页插件
pagehelper:
helperDialect: mysql
reasonable: true <build>
<plugins>
<!-- Spring Boot Maven plugin -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!-- MyBatis Generator plugin -->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
<overwrite>true</overwrite>
<verbose>true</verbose>
</configuration>
</plugin>
</plugins>
</build>The generator configuration file generatorConfig.xml defines JDBC connection details, target packages for POJOs, mappers, and Java client generators, and a wildcard table selection.
<generatorConfiguration>
<properties resource="generator/generator.properties"/>
<classPathEntry location="${classPathEntry}"/>
<context id="DB2Tables" targetRuntime="MyBatis3">
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/${db}?characterEncoding=utf-8"
userId="${userId}" password="${password}"/>
<javaModelGenerator targetPackage="${pojoTargetPackage}" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<sqlMapGenerator targetPackage="${mapperTargetPackage}" targetProject="src/main/resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<javaClientGenerator type="XMLMAPPER" targetPackage="${daoTargetPackage}" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<table tableName="%" schema="${db}"/>
</context>
</generatorConfiguration>The accompanying generator.properties file holds environment‑specific values such as the MySQL driver path, database name, credentials, and target package names.
# 请手动配置以下选项
# 数据库驱动:选择你的本地硬盘上面的数据库驱动包
classPathEntry = D:/CJH/maven-repository/mysql/mysql-connector-java/5.1.30/mysql-connector-java-5.1.30.jar
# 数据库名称、用户名、密码
db = db
userId = root
password = 123
# 生成pojo的包名位置 在src/main/java目录下
pojoTargetPackage = com.spring.demo.springbootexample.mybatis.po
# 生成DAO的包名位置 在src/main/java目录下
daoTargetPackage = com.spring.demo.springbootexample.mybatis.mapper
# 生成Mapper的包名位置 位于src/main/resources目录下
mapperTargetPackage = mapperRunning the generator is as simple as executing the Maven goal:
# 打开命令行 cd到项目pom.xml同级目录运行以下命令
mvn mybatis-generator:generate -eMyBatis mapper scanning is configured in application.yml :
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.spring.demo.springbootexample.mybatis.poA test controller demonstrates that the generated mapper works:
@Controller
public class TestController {
@Autowired
UserMapper userMapper;
@RequestMapping("/test")
@ResponseBody
public Object test(){
return userMapper.selectByExample(null);
}
}Swagger2 integration is achieved by adding a configuration class that builds a Docket bean with API metadata.
@Configuration
public class SwaggerConfig {
private final String version = "1.0";
private final String title = "SpringBoot示例工程";
private final String description = "API文档自动生成示例";
private final String termsOfServiceUrl = "http://www.kingeid.com";
private final String license = "MIT";
private final String licenseUrl = "https://mit-license.org/";
private final Contact contact = new Contact("calebman", "https://github.com/calebman", "[email protected]");
@Bean
public Docket buildDocket() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(buildApiInf())
.select().build();
}
private ApiInfo buildApiInf() {
return new ApiInfoBuilder().title(title).termsOfServiceUrl(termsOfServiceUrl).description(description)
.version(version).license(license).licenseUrl(licenseUrl).contact(contact).build();
}
}The main application class is annotated with @EnableSwagger2 to activate Swagger.
@SpringBootApplication
@EnableSwagger2
public class SpringBootExampleApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootExampleApplication.class, args);
}
}Multi‑environment profiles are defined using application-dev.yml , application-test.yml , and application-prod.yml . The default profile is set in application.yml with spring.profiles.active: dev . Each profile contains environment‑specific settings such as database URLs and credentials.
spring:
profiles:
active: devLogback is configured via logback-spring.xml to provide different logging behaviours per profile: console logging at INFO for development, file logging at WARN for testing, and ERROR‑only logging for production. The configuration uses Spring properties ${logdir} , ${appname} , and ${basepackage} defined in application.yml .
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<property name="maxsize" value="30MB"/>
<property name="maxdays" value="90"/>
<springProperty scope="context" name="logdir" source="resources.logdir"/>
<springProperty scope="context" name="appname" source="resources.appname"/>
<springProperty scope="context" name="basepackage" source="resources.basepackage"/>
...
<springProfile name="dev">
<root level="INFO">
<appender-ref ref="consoleLog"/>
</root>
<logger name="${basepackage}" level="DEBUG" additivity="false">
<appender-ref ref="consoleLog"/>
</logger>
</springProfile>
<springProfile name="test">
<root level="WARN">
<appender-ref ref="consoleLog"/>
<appender-ref ref="fileLog"/>
</root>
<logger name="${basepackage}" level="INFO" additivity="false">
<appender-ref ref="consoleLog"/>
<appender-ref ref="fileLog"/>
</logger>
</springProfile>
<springProfile name="prod">
<root level="ERROR">
<appender-ref ref="consoleLog"/>
<appender-ref ref="fileLog"/>
</root>
<logger name="${basepackage}" level="INFO" additivity="false">
<appender-ref ref="consoleLog"/>
<appender-ref ref="fileLog"/>
</logger>
</springProfile>
</configuration>Additional utility code shows how to load custom properties and implement a global exception handler.
@Component
@PropertySource(value = {"classpath:application.yml"}, encoding = "utf-8")
public class Config {
@Value("${resources.midpHost}")
private String midpHost;
public String getMidpHost() { return midpHost; }
} @ControllerAdvice
public class GlobalExceptionResolver {
Logger logger = LoggerFactory.getLogger(GlobalExceptionResolver.class);
@ExceptionHandler(value = Exception.class)
@ResponseBody
public WebResult exceptionHandle(HttpServletRequest req, Exception ex) {
ex.printStackTrace();
logger.error("未知异常", ex);
return WebResult.error(ERRORDetail.RC_0401001);
}
}The complete example project is open‑source on GitHub: https://github.com/calebman/spring-boot-example .
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.