Springboot总结

1.springboot概念

The primary goals of Spring Boot are:
To provide a radically faster and widely accessible ‘getting started’ experience for all Spring development.
To be opinionated out of the box, but get out of the way quickly as requirements start to diverge from the defaults.
To provide a range of non-functional features that are common to large classes of projects (e.g. embedded servers, security, metrics, health checks, externalized configuration).
Spring Boot does not generate code and there is absolutely no requirement for XML configuration.

Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。通过这种方式,Spring Boot致力于在蓬勃发展的快速应用开发领域(rapid application development)成为领导者。

2.springboot开发流程

2.1 创建maven项目

配置maven环境
在这里插入图片描述

2.2 引入依赖

2.2.1 配置parent(起步依赖)

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.10</version>
   </parent>

2.2.2 配置业务框架

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${project.mysql.version}</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>${project.druid.version}</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>${project.mybatis.version}</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${project.lombok.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${project.juint.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>${project.swagger.version}</version>
        </dependency>
    </dependencies>

2.2.3 配置版本号

 <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.mysql.version>8.0.28</project.mysql.version>
        <project.druid.version>1.2.8</project.druid.version>
        <project.mybatis.version>2.2.2</project.mybatis.version>
        <project.lombok.version>1.18.22</project.lombok.version>
        <project.juint.version>4.12</project.juint.version>
        <project.swagger.version>3.0.0</project.swagger.version>
    </properties>

2.2.4 打包

   <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
   </build>

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
若项目已经打包完毕,则可以部署项目
在这里插入图片描述

2.2.5 补充

倘若我们准备更换启动服务器

       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-undertow</artifactId>
        </dependency>

2.3 项目基本结构

在这里插入图片描述

2.4 Springboot的入口类

运行main方法的类
自动化配置

package com.dyit.springboot;

import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Main {
    public static void main(String[] args) {
        SpringApplication sa = new SpringApplication(Main.class);

        //sa.setBannerMode(Banner.Mode.OFF);
        sa.run(args);
    }
}

2.4.1@SpringBootApplication

@SpringBootApplication = @ComponentScan+@EnableAutoConfiguration+…

2.4.1.1 @ComponentScan

扫描容器(spring容器mvc+spring)中类
@Controller/@RestController
@Service
@Repository(用在持久层的接口上,这个注解是将接口的一个实现类交给spring管理)
@Component
在这里插入图片描述

2.4.1.2 @EnableAutoConfiguration

自动配置

2.5 配置banner

${AnsiColor.BRIGHT_BLUE}

//                          _ooOoo_                               //
//                         o8888888o                              //
//                         88" . "88                              //
//                         (| ^_^ |)                              //
//                         O\  =  /O                              //
//                      ____/`---'\____                           //
//                    .'  \\|     |//  `.                         //
//                   /  \\|||  :  |||//  \                        //
//                  /  _||||| -:- |||||-  \                       //
//                  |   | \\\  -  /// |   |                       //
//                  | \_|  ''\---/''  |   |                       //
//                  \  .-\__  `-`  ___/-. /                       //
//                ___`. .'  /--.--\  `. . ___                     //
//              ."" '<  `.___\_<|>_/___.'  >'"".                  //
//            | | :  `- \`.;`\ _ /`;.`/ - ` : | |                 //
//            \  \ `-.   \_ __\ /__ _/   .-` /  /                 //
//      ========`-.____`-.___\_____/___.-`____.-'========         //
//                           `=---='                              //
//      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^        //
//            ${AnsiColor.BRIGHT_RED}佛祖显灵       无病无灾     财源滚滚  大吉大利           ${AnsiColor.BRIGHT_BLUE} //

启动失败问题:APPLICATION FAILED TO START
Description:

Failed to configure a DataSource: ‘url’ attribute is not specified and no embedded datasource could be configured.

Reason: Failed to determine a suitable driver class

原因:没有配置DataSource
自动配置
解决方案:1.配置yml 2.暂时不配置DataSource

@SpringBootApplication(exclude = {
     DruidDataSourceAutoConfigure.class,
     DataSourceAutoConfiguration.class
})

2.6 springboot配置

在这里插入图片描述

2.6.1 调度

#  进行调度
spring:
  profiles:
    active: dev

2.6.2 运行环境

# 端口号配置,部署名称
server:
  port: 8099
  servlet:
    context-path: /ssm

#配置数据源
spring:
  datasource:
    druid:
      url: jdbc:mysql://localhost:3306/mybatis_db?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
      username: root
      password: 123456
      driver-class-name: com.mysql.cj.jdbc.Driver
#配置mybatis
mybatis:
  type-aliases-package: com.dyit.springboot.entity
  mapper-locations: classpath:mapper/*.mapper.xml
# 配置日志
logging:
  level:
    com.dyit.springboot:debug

2.6.3 测试环境

# 测试环境

2.6.4 上线环境

# 上线环境

2.7 实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
@Alias("Publisher")
public class Publisher {

    private int id;
    private String name;
    private String loc;
}

2.8 mapper接口

@Mapper
public interface IPublisherMapper {
    List<Publisher> findAll();
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.dyit.springboot.mapper.IPublisherMapper">
    <resultMap id="PublisherMap" type="Publisher">
        <id property="id" column="publisher_id"/>
        <result property="name" column="publisher_name"/>
        <result property="loc" column="publisher_loc"/>
    </resultMap>

    <select id="findAll" resultMap="PublisherMap">
        SELECT * FROM publisher_tab
    </select>

</mapper>

2.9 service类

public interface IPublisherService {
    List<Publisher> findAll();
}

实现类

@Service
@Transactional
@Slf4j
public class PublisherServiceImpl implements IPublisherService {

    @Autowired
    private IPublisherMapper mapper;

    @Transactional(propagation = Propagation.NEVER)
    @Override
    public List<Publisher> findAll() {
        List<Publisher> list = mapper.findAll();
        log.debug("查询所有部门:" + list);
        return list;
    }
}

2.10 单元测试

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@Slf4j
public class PublisherServiceImplTest {
    @Autowired
    private IPublisherService ips;

    @Test
    public void findAll() {
        List<Publisher> list = ips.findAll();
        log.debug("查询成功"+list);
    }
}

在这里插入图片描述

2.11 Controller类

dto类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class HttpRest {
    private Integer code;
    private String msg;
    private Object results;
    private Date date;
}

@RestController
@RequestMapping("/api/publisher")
@Slf4j
public class PublisherController {
    @Autowired
    private IPublisherService ips;

    @GetMapping("/findAll")
    public HttpRest findAll(){
        List<Publisher> list = ips.findAll();
        log.debug("获取所有出版社的信息");
        return new HttpRest(20001,"查询出版社信息成功",list,new Date());
    }
}

在这里插入图片描述
通过测试,我们发现了一个问题,时间总是比我们当前时间慢8个小时。

2.12 springboot处理时间问题

2.12.1 后台传输有时间

原因:spring整合json(Jackson),没有处理当前时区,
我们所处的时区(time-zone):东八区

解决方法:application-dev.yml文件设置json的时间日期:

spring:
  datasource:
    druid:
      url: jdbc:mysql://localhost:3306/mybatis_db?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
      username: root
      password: 123456
      driver-class-name: com.mysql.cj.jdbc.Driver
  jackson:
    date-format: yyyy-MM-dd HH:mm:ss
    time-zone: GMT+8

在这里插入图片描述

2.12.2 前端传输有时间

在这里插入图片描述
创建配置类,实现WebMvcConfigurer
覆盖addFormatter

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {

    private String name;
    private Date birth;
}
@RestController
@RequestMapping("/api/student")
@Slf4j
public class StudentController {
    @GetMapping("addStudent")
    public HttpRest addStudent(Student student){
        log.debug("学生信息"+student);
        return new HttpRest(20001,"添加学生信息成功",student,new Date());
    }
}
import lombok.SneakyThrows;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 配置类
 */
@Configuration
public class SsmConfiguration implements WebMvcConfigurer {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new Converter<String, Date>() {
            @Override
            @SneakyThrows
            public Date convert(String source) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date d = sdf.parse(source);
                return d;
            }
        });
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>日期页面</title>
</head>
<body>
    <form action="api/student/addStudent">
        <input type="text" placeholder="请输入要添加的学生名字" name="name">
        <input type="date" name="birth">
        <input type="submit" value="添加学生信息">

    </form>

</body>
</html>

在这里插入图片描述
常见的错误

服务器返回的状态码
200—OK
400—转换问题(时间)String—>Date
404—URL错误(资源位置错误)
405—前端请求方法(GET)后台(POST)
500—后台逻辑错误(空指针错误)

2.13 接口测试工具Swagger3

在这里插入图片描述

2.13.1 引入Swagger框架

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>${project.swagger.version}</version>
        </dependency>

2.13.2 配置swagger3

/**
 * Swagger配置类
 */
@Configuration
public class SwaggerConfiguration {

    public Docket createRestApi(){
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(Operation.class))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("springboot整合swagger3的接口文档")
                .description("描述图书馆管理的接口文档")
                .contact(new Contact("aaa","http://www.baidu.com","dyit@.com"))
                .version("1.0")
                .build();
    }
}
@Schema(description = "dto对象")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class HttpRest {
    @Schema(description = "后台返回代码")
    private Integer code;
    @Schema(description = "后台返回信息")
    private String msg;
    @Schema(description = "后台返回数据")
    private Object results;
    @Schema(description = "后台返回数据的时间")
    private Date date;
}
@RestController
@RequestMapping("/api/publisher")
@Slf4j
@Tag(name = "出版社模块")
public class PublisherController {
    @Autowired
    private IPublisherService ips;

    @Operation(summary = "获取此出版社信息方法")
    @GetMapping("/findAll")
    public HttpRest findAll(){
        List<Publisher> list = ips.findAll();
        log.debug("获取所有出版社的信息");
        return new HttpRest(20001,"查询出版社信息成功",list,new Date());
    }
}

运行

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值