Comprehensive Spring Boot Integration Guide: MyBatis, Druid, Redis, Swagger, Email, CORS, AOP and More

This article provides a step‑by‑step tutorial on building a Spring Boot project and configuring essential features such as starters, configuration properties, profiles, global exception handling, CORS, MVC interceptors, AOP, MyBatis‑Druid integration, Redis caching, email sending, and Swagger API documentation, complete with code examples and best‑practice tips.

Architecture Digest
Architecture Digest
Architecture Digest
Comprehensive Spring Boot Integration Guide: MyBatis, Druid, Redis, Swagger, Email, CORS, AOP and More

After finishing a deep dive into Spring source code, the author relaxes and then creates a small tool to render weekly report data, noting that front‑end development can be challenging.

The tutorial uses the book "Spring Boot + Vue Full‑Stack Development" as a reference and provides a concise cheat‑sheet for quick knowledge lookup.

Project Construction

Instead of using IDEA templates, generate a Spring Boot project via https://start.spring.io/, modify the group and artifact IDs, click Generate the project, download, and open it in IDEA. No additional configuration is required; simply run the Application class's run method.

Spring Boot Basic Configuration

The starter concept bundles required dependencies, reducing manual dependency management. Spring Boot follows the principle of "convention over configuration".

For example, to use Redis caching, older approaches required manual pom entries, property settings, Jedis connection creation, and custom connection‑pool management.

With Spring Boot, adding spring-boot-starter-data-redis to pom.xml and configuring properties in application.properties automatically creates a RedisAutoConfiguration bean, simplifying usage.

Spring Boot Starters

Starters encapsulate groups of dependencies, similar to Docker's packaging concept, providing a logical abstraction layer.

@SpringBootApplication Annotation

This meta‑annotation combines @SpringBootConfiguration, @EnableAutoConfiguration, and @ComponentScan, enabling automatic configuration and component scanning.

Web Container Configuration

Common server properties such as server.port, server.error.path, session timeout, context path, and Tomcat settings are listed with explanations.

HTTPS Configuration

Key properties include server.ssl.key-store, server.ssl.key-alias, and server.ssl.key-store-password. Refer to the "Spring Boot 使用SSL-HTTPS" article for details.

@ConfigurationProperties

When placed on a class or @Bean method, Spring Boot binds configuration properties prefixed with the specified value to the class fields, supporting simple types and collections.

@Configuration
@ConfigurationProperties(prefix = "spring.datasource")
public class DruidConfigBean {
    private Integer initialSize;
    private Integer minIdle;
    private Integer maxActive;
    private List<String> customs;
    // ...
}

Profile

Profiles enable environment‑specific configuration files named application-{profile}.properties. Activation can be done via spring.profiles.active, programmatic setAdditionalProfiles, or command‑line arguments.

@ControllerAdvice for Global Data

Used together with @ExceptionHandler, @ModelAttribute, and @InitBinder to handle cross‑cutting concerns.

@ControllerAdvice
public class CustomExceptionHandler {
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public void uploadException(MaxUploadSizeExceededException e, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.write("上传文件大小超出限制");
        out.flush();
        out.close();
    }
}

CORS Support

To resolve cross‑origin errors, add @CrossOrigin(origins = "http://localhost:3000") and set the response header Access-Control-Allow-Credentials: true on the controller method.

MVC Interceptor Registration

Implement HandlerInterceptor and register it via WebMvcConfigurer to intercept requests before and after controller execution.

public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        return true; // before controller
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        // after controller
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // after view rendering
    }
}

AOP Enablement

Add spring-boot-starter-aop dependency; Spring will automatically apply aspects defined with @Aspect.

MyBatis and Druid Integration

Add dependencies for mybatis-spring-boot-starter and druid-spring-boot-starter, then configure database and pool properties in application.properties. Place MyBatis XML mappers under resources and ensure they are scanned.

Redis Integration

Include spring-boot-starter-data-redis (excluding Lettuce) and jedis. Configure host, port, and pool settings, then autowire RedisTemplate or StringRedisTemplate to perform cache operations.

@Autowired
private RedisTemplate redisTemplate;
@Autowired
private StringRedisTemplate stringRedisTemplate;

@GetMapping("/testRedis")
public Book getForRedis() {
    ValueOperations<String, String> ops1 = stringRedisTemplate.opsForValue();
    ops1.set("name", "Go 语言实战");
    String name = ops1.get("name");
    System.out.println(name);
    ValueOperations ops2 = redisTemplate.opsForValue();
    Book book = (Book) ops2.get("b1");
    if (book == null) {
        book = new Book("Go 语言实战", 2, "none name", BigDecimal.ONE);
        ops2.set("b1", book);
    }
    return book;
}

Email Sending (HTML)

Add spring-boot-starter-mail and spring-boot-starter-thymeleaf. Configure SMTP settings (e.g., QQ mail) and use JavaMailSender with a Thymeleaf template to send styled emails.

Swagger Integration

Include springfox-swagger2 and springfox-swagger-ui dependencies, create a SwaggerConfig bean, and register resource handlers for the UI. Annotate controllers with @ApiOperation to generate interactive API docs.

Summary

The guide consolidates essential Spring Boot configurations and integrations, offering a practical foundation for developers to quickly spin up a functional backend with database access, caching, security, documentation, and email capabilities.

References

Spring Boot Starters

Spring Boot SSL‑HTTPS

ConfigurationProperties documentation

Cross‑origin request handling (CORS)

Spring Data Redis – RedisTemplate

Swagger2 integration tutorial

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

IntegrationSpring BootMyBatisSwaggerEmail
Architecture Digest
Written by

Architecture Digest

Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.