SpringBoot 系列教程(16章节全上篇)

1 SpringBoot的介绍

Spring Boot 是一个用于简化和加速构建基于 Spring 框架的应用程序的工具。它提供了一种样板化的配置和开箱即用的功能,让开发人员能够更快速地创建可独立运行的、生产级别的 Spring 应用程序。

主要特点:

  • 样板化配置: Spring Boot 的一个显著特点是它的样板化配置。它通过自动配置和约定大于配置的原则,大大减少了项目配置的繁琐。这使得传统的项目配置变得更加简单和统一。
  • 内置服务器: Spring Boot 默认内置了多个 Web 服务器(包括 Tomcat、Jetty 和 Undertow),使得开发人员在开发阶段无需手动部署项目到外部服务器,只需运行项目的 main 方法,就可以直接启动嵌入式服务器,项目就可以运行起来。
  • 总之,Spring Boot 提供了一个便捷的方式来构建 Spring 应用程序,减少了繁琐的配置步骤,提供了开箱即用的功能,使开发人员能够更专注于业务逻辑的实现,而不是配置和环境设置。这使得开发更加高效,也降低了项目的维护成本。

    2 搭建SpringBoot的开发环境

  • 配置jdk的版本,因为SpringBoot2依赖了spring5,spring5又依赖了jdk1.8,所以我们的项目至少是jdk1.8.
    pom.xml文件中修改jdk的版本。
  •   
        UTF-8
        1.8
        1.8
      
    
  • 引入依赖。引入一个就可以了。这一个就相当于spring的核心jar包和springmvc的相关jar包。
  • 
        org.springframework.boot
        spring-boot-starter-web
        2.1.4.RELEASE
    
    
  • 开发控制器类。跟以前一样。
  • 
    @RestController//@Controller+@ResponseBody
    public class UserController {
        @GetMapping("/users")//设置请求方式只能是get请求
        public Map test(String name){
            System.out.println(name+"==================");
            //响应的数据
            Map map=new HashMap();
            map.put("a","zhangsan");
            map.put("b","20");
            return map;
        }
    }
    
  • 写main方法启动tomcat。这时可以访问该项目了。
    注意:

  • 类名叫Application
  • 类必须建在com.ludao。只有建在这个包里面,SpringBoot才会扫描本包以及子包中的注解。
  • 在这类上面添加注解。@SpringBootApplication
  • @SpringBootApplication
    public class Application {
        public static void main(String[] args) {
            //启动SpringBoot框架
            SpringApplication.run(Application.class,args);
        }
    }
    
  • 测试运行。默认tomcat的端口号是8080,我们需要写配置文件对端口号进行修改。
    application.properties放在resources文件夹里面。
  • #tomcat的端口号
    server.port=8989
    #项目的项目名,以后我们访问该项目http://ip:port/context-path
    server.servlet.context-path=/SpringBoot_day1
    
    

    3 SpringBoot的配置文件

    有两种配置方式。

  • application.properties配置。
  • application.yml配置。
  • 两者配置的内容是一样的。只是配置方式不一样。

    yml用来替换properties文件。两者都叫application,放的位置也一样都在resources里面。

    server:
      port: 8989
      servlet:
        context-path: /SpringBoot_day1
    

    yml是通过缩进(两个空格)来指定关系的。

    4 mybatis跟SpringBoot集成

  • 引入依赖。
  • 
    
        org.mybatis.spring.boot
        mybatis-spring-boot-starter
        1.3.2
    
    
    
        mysql
        mysql-connector-java
        5.1.38
    
    
  • 在application.yml里面配置数据源信息。
  • #配置数据库的连接信息
    spring:
      datasource:
        url: jdbc:mysql://localhost:3306/idea_day1?useUnicode=true&characterEncoding=utf8
        username: root
        password: 123456
        driver-class-name: com.mysql.jdbc.Driver
    #给实体起别名,设置映射文件的路径。
    mybatis:
      type-aliases-package: com.ludao.entity
      mapper-locations: classpath:com/baizhi/dao/*.xml
    
  • 写实体类,dao接口,dao的mapper文件。
    跟以前一样
  • 在dao接口上面添加注解。
    @Mapper//这个注解是让SpringBoot识别dao接口,自动生成dao的实现类,并让spring管理起来。
    让spring管理dao有两个注解可以选择:

  • 在dao接口上面添加@Mapper,这种方式需要每个dao都添加。
  • 在SpringBoot的启动类上面扫描dao包。管理dao对象。
  • @SpringBootApplication
    @MapperScan("com.ludao.dao")//扫描dao包
    public class Application {
        public static void main(String[] args) {
            SpringApplication.run(Application.class,args);
        }
    }
    
  • 测试dao。
    参考下一个步骤,跟junit集成。
  • 5 SpringBoot跟junit进行集成测试

  • 引入依赖。
  • 
        
          junit
          junit
          4.12
          test
        
        
        
          org.springframework.boot
          spring-boot-starter-test
          2.1.4.RELEASE
        
    
  • 在测试类上使用注解。@SpringBootTest
  • @RunWith(SpringRunner.class)
    @SpringBootTest(classes = Application.class)
    public class TestDao {
        //飘红不影响使用
        @Autowired
        private StudentDao studentDao;
        @Test
        public void testSelectAll(){
            List students = studentDao.selectAll();
    
            students.forEach(System.out::println);
        }
        
    }
    

    6 SpringBoot和业务类的相关配置

    业务类的作用控制事务,mybatis插件分页。

    6.1 控制事务

  • 我们可以在类上面添加注解。@Transactional来标注这个类 中所有的方法都开启事务。
  • 我们可以在查询方法上面添加 @Transactional(readOnly=true)表示查询方法上面不使用回滚段以此来提高查询速度。@Transactional(propagation = Propagation.REQUIRED)表示增删改方法都必须使用事务。
  • 
    @Service
    @Transactional//表示在当前类中所有的方法都要开启事务
    public class StudentServiceImpl implements StudentService {
        @Autowired
        private StudentDao studentDao;
        @Transactional(readOnly = true)//查询方法的事务策略是只读
        @Override
        public List selectAll() {
            return studentDao.selectAll();
        }
        @Transactional(readOnly = true)
        @Override
        public PageInfo selectByPage(int curPage, int pageSize) {
            PageHelper.startPage(curPage,pageSize);
            List students = studentDao.selectAll();
            PageInfo pi=new PageInfo(students);
            return pi;
        }
    }
    
    

    6.2 使用mybatis的插件实现分页

  • 引入mybatis插件依赖。跟以前的依赖不一样。
  •     
          com.github.pagehelper
          pagehelper-spring-boot-starter
          1.2.5
        
    
  • 业务类的写法跟以前一样。
  • 7 SpringBoot里面使用过滤器

    前置知识:SpringBoot管理bean对象第一种方式是使用注解@Component ,另外一种方式如下:

    SpringBoot中的很多配置都是通过类来完成的。我们配置拦截器类的时候也是在config包里面添加一个配置类。

  • 定义过滤器,跟以前一样。
  • package com.ludao.filter;
    
    import javax.servlet.*;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    
    public class AccessControlAllowFilter implements Filter {
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
    
        }
    
        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        ....;
        chain.doFilter(request,response);
        }
    
        @Override
        public void destroy() {
    
        }
    }
    
    
  • 写配置类
  • @Configuration
    public class MywebConfig  implements WebMvcConfigurer {
        @Bean
        public FilterRegistrationBean filterRegist() {
            FilterRegistrationBean frBean = new FilterRegistrationBean();
            frBean.setFilter(new AccessControlAllowFilter());
            frBean.addUrlPatterns("/*");
            return frBean;
        }
    }
    

    8 jackson

    Jackson、Fastjson和Gson都是用于处理JSON(JavaScript Object Notation)的库,它们可以在Java对象与JSON数据之间进行转换。这些库提供了API,使您能够将Java对象转换为JSON字符串,以及将JSON字符串转换回Java对象。以下是对这三个库的简要介绍:

  • Jackson: Jackson是一个强大的、高性能的JSON处理库,广泛用于Java开发中。它提供了多种处理JSON的方式,包括数据绑定(将JSON数据映射到Java对象)、树模型(操作JSON数据的树结构)和流式处理(以事件形式处理JSON数据)。Jackson的速度和灵活性使其成为许多企业级应用的首选。

  • Fastjson: Fastjson是阿里巴巴开发的一个高性能的JSON处理库,专注于速度和性能。它支持将Java对象转换为JSON字符串,以及将JSON字符串转换为Java对象。由于其出色的性能,Fastjson在大数据处理和高并发场景中得到了广泛应用。

  • Gson: Gson是Google开发的JSON处理库,它提供了简单易用的API来进行Java对象和JSON之间的转换。Gson支持将Java对象序列化为JSON字符串,以及将JSON字符串反序列化为Java对象。尽管性能可能没有Jackson和Fastjson那么高,但Gson的简洁性和易用性使其成为许多项目的选择。

  • 本文介绍的是 Jackson。

    SpringBoot里面使用jackson设置日期属性常见方式有两种:

  • 在实体类的属性上添加注解。优先级高。
  • @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
    private Date birth;
    
  • 在yml配置文件中设置全局的日期格式。优先级低
  • spring:
      datasource:
        url: jdbc:mysql://localhost:3306/idea_day1?useUnicode=true&characterEncoding=utf8
        username: root
        password: 123456
        driver-class-name: com.mysql.jdbc.Driver
      jackson:
        date-format: yyyy-MM-dd
        time-zone: GMT+8