1.作用

便捷搭建基于Spring的工程脚手架,尽可能减少一切xml的配置

2.使用步骤
1.创建工程
2.添加启动器依赖
3.创建启动类
4.创建处理器Controller
5.测试
  • 创建Maven工程

  • 添加启动器依赖

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <!-- 父工程依赖,统一版本 -->
        <parent>
            <artifactId>spring-boot-starter-parent</artifactId>
            <groupId>org.springframework.boot</groupId>
            <version>2.7.0</version>
        </parent>
    
        <groupId>com.miaokela</groupId>
        <artifactId>springboot</artifactId>
        <version>1.0-SNAPSHOT</version>
        <packaging>jar</packaging>
    
        <!--  设置java版本  -->
        <properties>
            <java.version>1.8</java.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
        </dependencies>
    </project>
    
  • 创建启动类

    package com.miaokela;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    /**
     * SpringBootApplication
     */
    @SpringBootApplication
    public class App {
        public static void main(String[] args) {
            SpringApplication.run(App.class, args);
        }
    }
    
  • 创建Controller

    package com.miaokela.controller;
    
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class HelloController {
    
        @GetMapping("hello")
        public String hello() {
            return "hello world";
        }
    }
    
  • 在application.properties中设置端口

    server.port = 8081
    
3.Java代码方式配置

使用@Value获取配置文件配置项 结合@Bean注册组件到Spring

  • Java配置相关注解

    @Configuration // 声明一个配置类,代替xml文件
    @Bean // 声明在方法上,将方法返回值加入到Bean容器,代替Bean标签
    @value // 属性注入
    @PropertySource // 指定外部属性文件
    
  • Java代码配置数据库连接池,并在Controller中注入使用

    1.添加依赖;
    2.创建数据库;
    3.创建数据库连接参数配置文件 jdbc.properties;
    4.创建配置类
    5.改造Controller注入数据源,并使用
    
    • 添加依赖

      <dependency>
          <groupId>com.alibaba</groupId>
          <artifactId>druid</artifactId>
          <version>1.2.4</version>
      </dependency>
      
    • 创建数据库

    • 创建数据库连接参数配置文件

      jdbc.properties

      jdbc.driverClassName=com.mysql.jdbc.Driver
      jdbc.url=jdbc:mysql://127.0.0.1:3306/springboot
      jdbc.username=root
      jdbc.password=123456
      
    • 添加配置类

      package com.miaokela.config;
      
      import com.alibaba.druid.pool.DruidDataSource;
      import org.springframework.beans.factory.annotation.Value;
      import org.springframework.context.annotation.Bean;
      import org.springframework.context.annotation.Configuration;
      import org.springframework.context.annotation.PropertySource;
      
      import javax.sql.DataSource;
      
      @Configuration
      @PropertySource("classpath:jdbc.properties")
      public class JdbcConfig {
          @Value("${jdbc.url}")
          String url;
      
          @Value("${jdbc.driverClassName}")
          String driverClassName;
      
          @Value("${jdbc.username}")
          String username;
      
          @Value("${jdbc.password}")
          String password;
      
          @Bean
          public DataSource dataSource() {
              DruidDataSource druidDataSource = new DruidDataSource();
      
              druidDataSource.setDriverClassName(driverClassName);
              druidDataSource.setUrl(url);
              druidDataSource.setUsername(username);
              druidDataSource.setPassword(password);
      
              return druidDataSource;
          }
      }
      
    • 修改Controller

      controller.HelloController

      package com.miaokela.controller;
      
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.web.bind.annotation.GetMapping;
      import org.springframework.web.bind.annotation.RestController;
      
      import javax.sql.DataSource;
      
      @RestController
      public class HelloController {
      
          @Autowired
          private DataSource dataSource;
      
          @GetMapping("hello")
          public String hello() {
              System.out.println(dataSource);
              return "hello world";
          }
      }
      
  • Spring Boot优雅属性注入方式

    将配置文件配置项读取到一个对象中
    注解默认支持.properties与.yml

    • 配置类

      config.JdbcConfig

      package com.miaokela.config;
      
      import com.alibaba.druid.pool.DruidDataSource;
      import org.springframework.boot.context.properties.ConfigurationProperties;
      import org.springframework.context.annotation.Bean;
      import org.springframework.context.annotation.Configuration;
      
      import javax.sql.DataSource;
      
      @Configuration
      public class JdbcConfig {
          @Bean
          @ConfigurationProperties(prefix = "jdbc")
          public DataSource dataSource() {
              return new DruidDataSource();
          }
      }
      

      application.properties

      jdbc.driverClassName=com.mysql.jdbc.Driver
      jdbc.url=jdbc:mysql://127.0.0.1:3306/springboot
      jdbc.username=root
      jdbc.password=123456
      
      server.port=8081
      
  • yaml多文件配置

    yaml与properties配置文件除了展示形式不相同以外,其他功能和作用都是一样的,读取方式不变

    jdbc:
        driverClassName: com.mysql.jdbc.Driver
        url: jdbc:mysql://127.0.0.1:3306/springboot
        username: root
        password: 123456
    
    • 多文件配置要求
      1.名称必须为application-***.yml
      2.必须在application.yml中激活
      
4.lombok应用

简化POJO类
插件工具类包,提供@Data,@Getter等注解去简化构造方法,get/set等方法

  • 步骤

    1.IDE安装lombok插件
    2.添加依赖坐标
    3.改造实体类
    
    • 导入坐标

      <dependency>
          <groupId>org.projectlombok</groupId>
          <artifactId>lombok</artifactId>
      </dependency>
      
    • 实体类

      entity.User

      @Data // 在编译阶段会根据注解自动生成对应的方法:get/set/hashCode/equels/toString等方法
      public class User {
          private Long id;
          private String userName;
          private String password;
          private String name;
          private Integer age;
          private Integer sex;
          private Date birthday;
          private String note;
          private Date created;
          private Date updated;
      }
      
5.Spring Boot整合MVC
  • 整合Spring MVC端口和静态资源

    • 修改tomcat端口

      properties

      server.port = 8081
      

      yaml

      server:
          port: 8081
      
      • 访问项目中的静态资源
  • 整合 Spring-MVC拦截器

    • 步骤

      1.编写拦截器 实现接口HandlerInterceptor
      2.编写配置类 WebMvcConfigurer, 在类中添加各种组件
      3.测试
      
    • 编写拦截器

      interceptor.MyInterceptor 拦截器类

      import lombok.extern.slf4j.Slf4j;
      import org.springframework.web.servlet.HandlerInterceptor;
      import org.springframework.web.servlet.ModelAndView;
      
      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;
      
      @Slf4j
      public class MyInterceptor implements HandlerInterceptor {
          @Override
          public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
              log.debug("preHandle");
              return HandlerInterceptor.super.preHandle(request, response, handler);
          }
      
          @Override
          public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
              log.debug("postHandle");
              HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
          }
      
          @Override
          public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
              log.debug("afterCompletion");
              HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
          }
      }
      

      config.MvcConfig 配置类

      package com.miaokela.config;
      
      import com.miaokela.interceptor.MyInterceptor;
      import org.springframework.context.annotation.Bean;
      import org.springframework.context.annotation.Configuration;
      import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
      import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
      import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
      
      @Configuration
      public class MvcConfig implements WebMvcConfigurer {
          // 注册拦截器
          @Bean
          public MyInterceptor myInterceptor() {
              return new MyInterceptor();
          }
          // 添加拦截器到Spring MVC拦截器链
          public void addInterceptors(InterceptorRegistry registry) {
              registry.addInterceptor(myInterceptor()).addPathPatterns("/*");
          }
      }
      
  • 整合事务与连接池

    配置Spring Boot自带默认的hikari连接池和使用@Transactional注解

    事务配置:
    1.添加事务相关的启动器依赖,mysql依赖
    2.编写UserService使用事务注解@Transactional
    数据库连接池hikari配置
    
    • 添加依赖坐标

      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-jdbc</artifactId>
      </dependency>
      
    • 编写UserService

        package com.miaokela.service;
      
        import com.miaokela.domain.User;
      
        public class UserService {
            // 根据id查询
            public User queryById(Long id) {
                return new User();
            }
            @Transactional // 添加事务
            public void saveUser(User user) {
                System.out.println("新增用户");
            }
        }
      
    • hikari配置

      spring.datasource.driver-class-name=com.mysql.jdbc.Driver
      spring.datasource.url=jdbc:mysql://127.0.0.1:3306/springboot
      spring.datasource.username=root
      spring.datasource.password=123456
      
6.Spring Boot整合Mybatis

配置整合包,设置mabatis实体类别名,输出执行sql语句配置项

  • 步骤

    1.添加启动器依赖 mybatis提供
    2.配置Mybatis:实体类别名,日志,映射文件
    3.配置MapperScan
    
    • 添加启动器依赖

      <dependency>
          <groupId>org.mybatis.spring.boot</groupId>
          <artifactId>mybatis-spring-boot-starter</artifactId>
          <version>2.2.2</version>
      </dependency>
      
    • 配置Mybatis

      # 配置实体类别名包
      mybatis.type-aliases-package=com.mkl.domain
      mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdoutImpl
      
    • 添加Mapper接口

      UserMapper

      package com.miaokela.mapper;
      
      import org.apache.ibatis.annotations.Mapper;
      
      @Mapper
      public interface UserMapper {
      }
      
    • 主运行文件中添加Mapper扫描

      @SpringBootApplication
      @MapperScan("com.mkl.mapper")
      public class App {
          public static void main( String[] args ) {
              SpringApplication.run(App.class, args);
          }
      }
      
  • 使用通用Mapper

    配置通用mapper组件到Spring Boot项目中并使用Mapper接口
    实现自动拼接sql语句,所有Mapper都不需要编写任何方法(生气了语句),提高开发效率

    1.添加启动器依赖
    2.改造UserMapper继承Mapper<User>;
    3.修改App中Mapper扫描注解
    4.修改User实体类添加jpa注解
    5.改造UserService实现业务
    
    • 添加启动器依赖

      通用mapper

      <dependency>
          <groupId>tk.mybatis</groupId>
          <artifactId>mapper-spring-boot-starter</artifactId>
          <version>4.2.1</version>
      </dependency>
      
    • 添加Mapper扫描注解

      package com.miaokela.mapper;
      
      import org.apache.ibatis.annotations.Mapper;
      
      @Mapper
      public interface UserMapper {
      }
      
    • 修改Dao

      domain.User

      package com.miaokela.domain;
      
      import lombok.Data;
      import tk.mybatis.mapper.annotation.KeySql;
      
      import javax.persistence.Column;
      import javax.persistence.Id;
      import javax.persistence.Table;
      
      @Data
      @Table(name="springboot")
      public class User {
          @Id
          @KeySql(useGeneratedKeys=true) // 主键回填
          private Long id;
      
          @Column
          private String name;
          private String sex;
      }
      
posted on 2022-09-22 00:02  _tiny_coder  阅读(31)  评论(0编辑  收藏  举报