• Spring Boot 2.x基础教程


    一、简介

    1. Spring Boot 2.x 简介

    Spring Boot是一个基于Spring框架的快速Web开发框架,采用约定大于配置的方式进行构建。简化了Spring应用程序的开发过程,并持续推出新的版本以满足当下开发的需要。

    2. Spring Boot 2.x 特点

    • 简化Spring应用程序开发流程
    • 自动配置Spring应用程序
    • 内嵌Servlet容器,无需部署war包
    • 提供管理端点,便于监控应用程序运行状况
    • 支持各类组件的集成,如ORM、模板引擎等

    3. Spring Boot 2.x 与 Spring Framework 的关系

    Spring Boot是构建在Spring Framework之上的框架。其中,Spring Framework提供了基础的IoC、AOP、事件、数据访问、Web框架和测试等支持;而Spring Boot则对Spring Framework进行了封装,进一步简化了Spring应用程序的构建。

    二、Spring Boot 2.x 环境搭建

    1. JDK环境安装与配置

    首先,需要安装Java Development Kit(JDK)。可以通过Oracle官网下载并安装最新版的JDK,然后在环境变量中配置JDK的安装路径。

         <dependency>
             <groupId>org.springframework.bootgroupId>
             <artifactId>spring-boot-starter-webartifactId>
             <version>2.5.0version>
         dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    2. Maven环境安装与配置

    接下来,需要安装Maven。可以通过Apache官网下载并安装最新版的Maven,然后在环境变量中配置Maven的安装路径。

    3. Spring Boot 2.x 项目创建

    最后可以使用Spring Initializr创建Spring Boot项目。在Spring Initializr的官网(https://start.spring.io/)中,选择需要的项目配置和依赖项,然后点“生成”即可。生成的项目包含了基础的Spring Boot配置和依赖项,可以直接用于开发。

    三、核心功能

    1. 配置文件及其加载顺序

    a. YAML 文件格式

    # YAML配置文件示例
    server:
      port: 8080
    spring:
      datasource:
        url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
        username: root
        password: test
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    注释:通过YAML文件配置serverspring的相关属性,其中datasource为数据库连接属性配置。

    b. 属性配置文件( .properties )

    # .properties配置文件示例
    server.port=8080
    spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
    spring.datasource.username=root
    spring.datasource.password=test
    
    • 1
    • 2
    • 3
    • 4
    • 5

    注释:通过.properties配置文件配置serverspring的相关属性,其中datasource为数据库连接属性配置。

    2. 日志管理

    a. Spring Boot 日志框架选用

    Spring Boot默认采用logback进行日志输出,你也可以切换为其他日志框架,比如Log4j2或者JUL等。

    b. 自定义日志

    使用Slf4j来封装日志内容,并搭配对应的日志框架进行输出。

    // 引入Slf4j
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.stereotype.Service;
    
    @Service
    @Slf4j
    public class UserService {
    
        public void login(String username, String password) {
            log.info("用户{}正在登录...", username);
            // do something
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    注释:使用@Slf4j注解引入Slf4j日志封装,在需要输出日志的地方使用log.info等方法进行输出。

    3. Spring Boot 2 热部署实现

    a. devtools的引入

    使用devtools可以实现Spring Boot项目的热部署功能,可以在开发阶段提高调试效率。

    
    <dependency>
       <groupId>org.springframework.bootgroupId>
       <artifactId>spring-boot-devtoolsartifactId>
       <optional>trueoptional>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    注释:通过Maven引入devtools依赖。

    b. 使用方法与注意事项

    在配置文件中加入如下属性:

    # 配置热部署属性
    spring.devtools.restart.enabled=true
    spring.devtools.restart.exclude=static/**,public/**
    
    • 1
    • 2
    • 3

    注意事项:在使用时,需要手动编译一次代码才能生效。

    4. Spring Boot 2.x 中的 AOP

    a. 切面的定义和使用

    使用@Aspect注解定义切面类,使用@Before@After@Around等注解来定义不同类型的通知,并通过@Pointcut注解定义切点。如下:

    // 定义切面类
    @Aspect
    @Service
    @Slf4j
    public class LogAspect {
    
        // 定义切点
        @Pointcut("execution(* com.example.demo.service..*.*(..))")
        public void point() {}
    
        // 定义前置通知
        @Before("point()")
        public void before() {
            log.info("before aspect.");
        }
    
        // 定义后置通知
        @After("point()")
        public void after() {
            log.info("after aspect.");
        }
    
        // 定义环绕通知
        @Around("point()")
        public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
            log.info("before around aspect.");
            Object obj = joinPoint.proceed();
            log.info("after around aspect.");
            return obj;
        }
    }
    
    • 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

    使用切面:

    @Service
    @Slf4j
    public class UserService {
    
        @Autowired
        private UserDao userDao;
    
        // 使用切面
        @LogAspect
        public void login(String username, String password) {
            log.info("用户{}正在登录...", username);
            // do something
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    注释:使用@Aspect注解定义切面类,通过@Pointcut注解定义切点,使用@Before@After@Around等注解来定义不同类型的通知,在需要使用切面的方法上加上自定义的注解即可。

    四、数据访问

    1. Spring Boot 2.x 与 JPA

    a. JPA简介

    JPA是 Java Persistence API 的缩写,是一套ORM规范,为开发者提供了一个简单优雅的方式来管理Java应用中的关系型数据。

    b. Spring Boot 2.x 使用JPA基本配置

    在Spring Boot项目中使用JPA,需要添加以下依赖:

    
    <dependency>
       <groupId>org.springframework.bootgroupId>
       <artifactId>spring-boot-starter-data-jpaartifactId>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    同时在配置文件中进行数据库配置:

    # jpa 数据库配置
    spring.datasource.driverClassName=com.mysql.jdbc.Driver
    spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false
    spring.datasource.username=root
    spring.datasource.password=test
    spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    注释:通过Maven引入spring-boot-starter-data-jpa依赖,并在配置文件中进行数据库配置。

    2. Spring Boot 2.x 与 MyBatis

    a. MyBatis 简介

    MyBatis是一种持久层ORM框架,它对JDBC的操作数据库的过程进行封装,提供了更加简单、易读、易维护的方式。

    b. Spring Boot 2.x 整合 MyBatis

    在Spring Boot项目中整合MyBatis,需要添加以下依赖:

    
    <dependency>
       <groupId>org.mybatis.spring.bootgroupId>
       <artifactId>mybatis-spring-boot-starterartifactId>
       <version>2.1.3version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    同时在配置文件中进行数据库配置:

    # MyBatis及数据库配置
    # MyBatis的mapper文件的路径 
    mybatis.mapper-locations=classpath:mapper/*.xml
    # 数据源配置
    spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false
    spring.datasource.driver-class-name=com.mysql.jdbc.Driver
    spring.datasource.username=root
    spring.datasource.password=test
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    注释:通过Maven引入mybatis-spring-boot-starter依赖,并在配置文件中进行数据库配置。

    3. Spring Boot 2.x 与 Druid 数据源

    a. Druid 简介

    Druid 是阿里开源平台上一个数据库连接池实现,结合了 C3P0、DBCP 等 DB 连接池的优点,同时加入了日志监控。

    b. Spring Boot 2.x 整合 Druid

    在Spring Boot项目中整合Druid,需要添加以下依赖:

    
    <dependency>
       <groupId>com.alibabagroupId>
       <artifactId>druid-spring-boot-starterartifactId>
       <version>1.2.5version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    同时在配置文件中进行数据库配置:

    # druid 数据库配置
    spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
    spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
    spring.datasource.username=root
    spring.datasource.password=test
    
    # druid 配置
    spring.datasource.druid.driver-class-name=com.mysql.jdbc.Driver
    spring.datasource.druid.initial-size=1
    spring.datasource.druid.min-idle=1
    spring.datasource.druid.max-active=20
    spring.datasource.druid.max-wait=60000
    spring.datasource.druid.time-between-eviction-runs-millis=60000
    spring.datasource.druid.min-evictable-idle-time-millis=300000
    spring.datasource.druid.validation-query=SELECT 1 FROM DUAL
    spring.datasource.druid.test-while-idle=true
    spring.datasource.druid.test-on-borrow=false
    spring.datasource.druid.filters=stat,wall
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    注释:通过Maven引入druid-spring-boot-starter依赖,并在配置文件中进行数据库配置。

    五、Spring Boot 2.x 与 Web

    1. Spring Boot 2.x Web 封装

    a. Spring Boot 自带web应用服务器

    Spring Boot 默认会使用嵌入式 Tomcat 作为Web 应用服务器,而无需外部部署。当然,你也可以使用 Jetty 或 Undertow 作为替代品。

    b. 四种常见的响应方式

    在Spring Boot中通常会有以下4种常见的响应方式:

    1. 返回 Model 层数据
    @GetMapping("/model")
    public String model(Model model) {
        model.addAttribute("name", "John");
        return "hello";
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    上面代码中,我们将Model对象中的属性"name"设置为"John",然后返回一个名为"hello"的模板。Spring Boot 会自动根据模板渲染出相应的HTML。

    2. 直接返回字符串
    @GetMapping("/response")
    @ResponseBody
    public String response() {
        return "Hello World!";
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    上面代码中,我们直接返回一个字符串"Hello World!",Spring Boot 会将其转化为HTTP Response输出到客户端。

    3. 返回 JSON 数据
    @GetMapping("/json")
    @ResponseBody
    public Map<String, Object> json() {
        Map<String, Object> map = new HashMap<>();
        map.put("name", "John");
        map.put("age", 30);
        map.put("gender", "Male");
        return map;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    上面代码中,我们返回一个Map类型的JSON数据,其中包含三个属性:name、age 和 gender。

    4. 返回 HTTP 状态码
    @GetMapping("/status")
    public ResponseEntity<String> status() {
        return new ResponseEntity<>("Hello World!", HttpStatus.OK);
    }
    
    • 1
    • 2
    • 3
    • 4

    上面代码中,我们返回一个HTTP OK状态并携带"Hello World!"的字符串。

    2. Spring Boot 2.x 与 JSP

    a. JSP 简介

    JSP(Java Server Pages)是一种在HTML(或XML)文档中嵌入Java代码的技术。它是Servlet API之上的一种封装,可用于开发动态Web页面。
    JSP 允许您在 HTML 页面中嵌入 Java 代码,这样您就能够在页面显示动态内容。

    b. Spring Boot 2.x使用JSP

    首先在工程的pom.xml里添加对jsp 支持及Tomcat Embed Jasper 的依赖:

    <dependency>
        <groupId>org.apache.tomcat.embedgroupId>
        <artifactId>tomcat-embed-jasperartifactId>
        <scope>providedscope>
    dependency>
    
    <dependency>
        <groupId>javax.servletgroupId>
        <artifactId>jstlartifactId>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    在application.properties里添加以下配置:

    spring.mvc.view.prefix=/WEB-INF/jsp/
    spring.mvc.view.suffix=.jsp
    
    • 1
    • 2

    创建 JSP 文件(/src/main/webapp/WEB-INF/jsp/hello.jsp):

    
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Hello JSPtitle>
    head>
    <body>
        <h1>Hello, <%= request.getAttribute("name") %>!h1>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    添加Controller代码:

    @Controller
    public class HelloController {
    
        @RequestMapping("/hello")
        public String hello(Model model) {
            model.addAttribute("name", "John");
            return "hello";
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    访问 http://localhost:8080/hello 就可以了。

    3. Spring Boot 2.x 静态资源处理

    a. 静态资源访问

    Spring Boot 2.x默认会在如下路径中查找静态资源:

    classpath:/META-INF/resources/
    classpath:/resources/
    classpath:/static/
    classpath:/public/
    
    • 1
    • 2
    • 3
    • 4

    例如,你可以在src/main/resources/static/目录下创建一个名为logo.png的图片文件,并通过URL http://localhost:8080/logo.png访问它。

    六、Spring Boot 2.x 高级特性

    1. Spring Boot 2.x Actuator 扩展

    a. actuator 的作用

    Actuator 用于监控和管理 Spring Boot 应用程序,它提供了很多用于检查应用程序运行状况的功能,包括应用程序健康状况、指标收集和暴露、日志配置等功能。

    b. actuator 的使用方法

    1. 在pom.xml中引入 actuator的依赖:

      <dependency>
          <groupId>org.springframework.bootgroupId>
          <artifactId>spring-boot-starter-actuatorartifactId>
      dependency>
      
      • 1
      • 2
      • 3
      • 4
    2. 在application.properties文件中开启或关闭 Actuator 功能:

      management.endpoint.health.show-details=always
      
      • 1

      以上示例表示开启健康状况检查功能,并显示详细信息。

    3. 访问以下 URL 查看 Actuator 的功能列表:

      http://localhost:8080/actuator
      
      • 1

    2. Spring Boot 2.x 多环境配置

    a. 执行环境分类

    Spring Boot 环境定义有以下 4 种:

    • development
    • testing
    • staging
    • production

    b. 配置文件的优先级

    Spring Boot 支持多个 profile 的配置文件,文件名必须以 application-{profile}.properties 命名,其中 profile 可以是上述环境分类之一。

    当存在多个 profile 时,配置文件的优先级由高到低如下:

    1. application-{profile}.yml
    2. application-{profile}.properties
    3. application.yml
    4. application.properties

    3. Spring Boot 2.x 集成 Quartz

    a. Quartz 的简介

    Quartz 是一个功能强大的作业调度框架,可用于创建简单或复杂的定时任务,支持集群和分布式部署。

    b. Spring Boot 2.x 集成 Quartz

    1. 在pom.xml中引入 quartz 和 quartz-jobs 的依赖:

      <dependency>
         <groupId>org.quartz-schedulergroupId>
         <artifactId>quartzartifactId>
         <version>2.3.1version>
      dependency>
      <dependency>
         <groupId>org.quartz-schedulergroupId>
         <artifactId>quartz-jobsartifactId>
         <version>2.3.1version>
      dependency>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
    2. 在application.properties文件中配置 Quartz:

      # Quartz 配置
      spring.quartz.job-store-type=jdbc
      spring.quartz.jdbc.initialize-schema=always
      spring.quartz.properties.org.quartz.threadPool.threadCount=10
      
      • 1
      • 2
      • 3
      • 4
    3. 创建 Job 类:

      @Component
      public class MyJob implements Job {
      
         @Override
         public void execute(JobExecutionContext context) throws JobExecutionException {
            // 需要执行的任务逻辑
         }
         
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
    4. 创建 JobDetail 和 Trigger,并将它们注册到 Scheduler 中:

      @Configuration
      public class QuartzConfig {
      
         @Autowired
         private MyJob myJob;
      
         @Bean
         public JobDetail jobDetail() {
            return JobBuilder.newJob(myJob.getClass())
               .withIdentity("myJob")
               .storeDurably()
               .build();
         }
      
         @Bean
         public Trigger trigger(JobDetail job) {
            return TriggerBuilder.newTrigger()
               .forJob(job)
               .withIdentity("myJobTrigger")
               .withSchedule(CronScheduleBuilder.cronSchedule("0 0 12 * * ?"))
               .build();
         }
      
         @Bean
         public Scheduler scheduler(Trigger trigger, JobDetail job, DataSource dataSource) throws SchedulerException {
            SchedulerFactory schedulerFactory = new StdSchedulerFactory();
            Scheduler scheduler = schedulerFactory.getScheduler();
            scheduler.setDataSource(dataSource);
            scheduler.scheduleJob(job, trigger);
            return scheduler;
         }
         
      }
      
      • 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
  • 相关阅读:
    详解MySQL的MVCC(ReadView部分解析C++源码)
    【Redis学习1】Redis持久化机制详解
    PostgreSQL的学习心得和知识总结(一百一十一)|内核级自上而下完美实现PostgreSQL数据库 日志格式tsvlog 的实现方案
    我真的理解了背包dp问题吗?
    [STL]map与set
    23种设计模式--简单工厂模式、工厂方法模式、抽象工厂模式
    听说你要删库跑路了?这篇Linux脚本请收好
    Pycharm常用快捷键和替换正则表达式
    vue-devTools Chrome安装配置
    LeetCode39 组合总和
  • 原文地址:https://blog.csdn.net/u010349629/article/details/130875502