SpingBoot的使用浅析

SpingBoot的使用浅析

1、springboot简介

​ 众所周知 Spring 应用需要进行大量的配置,各种 XML 配置和注解配置让人眼花缭乱,且极容易出错,因此 Spring 一度被称为“配置地狱”。

​ 为了简化 Spring 应用的搭建和开发过程,Pivotal 团队在 Spring 基础上提供了一套全新的开源的框架,它就是 Spring Boot。

​ Spring Boot 具有 Spring 一切优秀特性,Spring 能做的事,Spring Boot 都可以做,而且使用更加简单,功能更加丰富,性能更加稳定而健壮。随着近些年来微服务技术的流行,Spring Boot 也成为了时下炙手可热的技术。

​ Spring Boot 提供了大量开箱即用(out-of-the-box)的依赖模块,例如 spring-boot-starter-redis、spring-boot-starter-data-mongodb 和 spring-boot-starter-data-elasticsearch 等。这些依赖模块为 Spring Boot 应用提供了大量的自动配置,使得 Spring Boot 应用只需要非常少量的配置甚至零配置,便可以运行起来,让开发人员从 Spring 的“配置地狱”中解放出来,有更多的精力专注于业务逻辑的开发。

2、 Spring Boot 的特点

1. 独立运行的 Spring 项目

​ Spring Boot 可以以 jar 包的形式独立运行,Spring Boot 项目只需通过命令“ java–jar xx.jar” 即可运行。

2. 内嵌 Servlet 容器

​ Spring Boot 使用嵌入式的 Servlet 容器(例如 Tomcat、Jetty 或者 Undertow 等),应用无需打成 WAR 包 。

3. 提供 starter 简化 Maven 配置

​ Spring Boot 提供了一系列的“starter”项目对象模型(POMS)来简化 Maven 配置。

4. 提供了大量的自动配置

​ Spring Boot 提供了大量的默认自动配置,来简化项目的开发,开发人员也通过配置文件修改默认配置。

5. 自带应用监控

​ Spring Boot 可以对正在运行的项目提供监控。

6. 无代码生成和 xml 配置

​ Spring Boot 不需要任何 xml 配置即可实现 Spring 的所有配置。

3、创建SpringBoot项目

在能够联网的情况下创建的SpringBoot项目

请添加图片描述

创建一个controller类

请添加图片描述

@RestController
public class HelloController {
    @GetMapping("/hello")
    public Map<String,Object> hello(){
        Map<String,Object> map = new HashMap<>();
        map.put("姓名","海绵宝宝");
        map.put("age",500);
        return map;
    }
}

在Application中直接运行,应为SpringBoot内置了Tomcat,所以不需要配置Tomcat。

请添加图片描述

这样就表示该项目运行成功,去浏览器中查看
请添加图片描述

4、Spring Boot的全局配置文件

​ Spring Boot 提供了大量的自动配置,极大地简化了spring 应用的开发过程,当用户创建了一个 Spring Boot 项目后,即使不进行任何配置,该项目也能顺利的运行起来。当然,用户也可以根据自身的需要使用配置文件修改 Spring Boot 的默认设置。

SpringBoot 默认使用以下 2 种全局的配置文件,其文件名是固定的。

  • application.properties
  • application.yml

第一种:application.properties文件

# 自定义Tomcat端口号
server.port=8081

第一种:application.yml文件

# 自定义Tomcat端口号
server:
  port: 8082

两种配置文件可以同时存在,而且必须以application命名,内容可以相同也可以不同。相同时,properties的优先级高;不同时,会有两个文件中的不同信息合并在一起的效果

5、读取SpringBoot文件中的信息

读取SpringBoot配置文件需要通过@PropertiesConfiguration或者@Value注解。前者在类上使用,后者只能放在我们的类属性上。而且它只能读取基本类型和字符串类型。读取配置文件中的信息时,要求配置文件中的变量名必须和实体类中的变量名保持一致,否则会读取失败,该值为空

application.properties

# 自定义的配置信息
student.name=KangKang
student.age=30
student.hobby[0]=swing
student.hobby[1]=writer

entity

@Data
@Component // 该类对象将交付于Spring容器来进行管理
@ConfigurationProperties(prefix = "student") // 读取SpringBoot配置文件中,以student开始的信息
public class Student {
    private String name;
    private Integer age;
    private String[] hobby;
}

Controller

@Autowired //spring容器自动注入该对象
private Student student;
@RequestMapping(value = "getInfo")
public Student getInfo(){
    return student;
}

请添加图片描述

6、SpringBoot整合数据源

数据源即数据库,SpringBoot整合数据源也就是链接数据库,对数据库信息进行CRUD操作

1、引入依赖

<!--加入数据源的启动依赖: springboot启动时会加载对应的自动装配类。-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.2</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<!--导入阿里巴巴的数据库连接池druid-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.2.8</version>
</dependency>

2、在application.properties中配置数据源信息

spring.datasource.druid.url=jdbc:mysql://localhost:3306/mydb?serverTimezone=Asia/Shanghai
spring.datasource.druid.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.druid.username=root
spring.datasource.druid.password=123456
# 初始化连接池个数
spring.datasource.druid.initial-size=5
# 最大活跃数
spring.datasource.druid.max-active=8
# 最大等待时间 毫米
spring.datasource.druid.max-wait=5000
# 最小闲置个数
spring.datasource.druid.min-idle=3
# mapper文件的映射路径
mybatis.mapper-locations=classpath:mapper/*.xml

3、在主启动类上加注解

@SpringBootApplication
@MapperScan(basePackages = "com.zzs.mapper")  //为指定的包下的接口生成代理实现类
public class Application {

    public static void main(String[] args) {
        //  加载那含有@SpringBootApplication注解的类
        SpringApplication.run(SpringbootApplication.class, args);
    }         
}

4、测试

entity

@Data
public class Student {
    private Integer id;
    private String name;
    private Integer tid;
}

mapper层

@Component
public interface StudentMapper {
    int deleteById(Integer id);
}

controller

@RestController
public class HelloController {
    @Autowired
       StudentMapper studentMapper;
    @GetMapping("deleteById")
    public void deleteById(Integer id){
        int i = studentMapper.deleteById(id);
        System.out.println(i);
    }
}

7、整合PageHelper分页

1、引入pagehelper分页依赖

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.4.2</version>
</dependency>

2、测试

mapper

@Component
public interface StudentMapper {
    Student findById(Integer id);
    List<Student> findAll();
}

controller

@Test
public void findAll(){
    PageHelper.startPage(1,2);
    List<Student> list = studentMapper.findAll();
    PageInfo<Student> pageInfo = new PageInfo<>(list);
    System.out.println("当前页码"+pageInfo.getPageNum());
    System.out.println("总条数"+pageInfo.getTotal());
    System.out.println("每页数量"+pageInfo.getPageSize());
}

8、整合API文档–swagger2

​ 当下很多公司都采取前后端分离的开发模式,前端和后端的工作由不同的工程师完成。在这种开发模式下,维持一份及时更新且完整的 Rest API 文档将会极大的提高我们的工作效率。传统意义上的文档都是后端开发人员手动编写的,相信大家也都知道这种方式很难保证文档的及时性,这种文档久而久之也就会失去其参考意义,反而还会加大我们的沟通成本。而 Swagger 给我们提供了一个全新的维护 API 文档的方式。

1、引入swagger2依赖

<dependency>
    <groupId>com.spring4all</groupId>
    <artifactId>swagger-spring-boot-starter</artifactId>
    <version>1.9.1.RELEASE</version>
</dependency>
<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>swagger-bootstrap-ui</artifactId>
    <version>1.7.8</version>
</dependency>

2、配置swagger

config

@Configuration
public class SwaggerConfig {
    @Bean
    public Docket docket(){
        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
            	.select()
         		.apis(RequestHandlerSelectors.basePackage("com.zzs.controller"))// 为指定包生成类接口文档
                .build();
        return docket;
    }

    // 自己定义接口信息
    private ApiInfo apiInfo(){
        Contact DEFAULT_CONTACT  = new Contact("海绵宝宝去抓水母吧", "http://www.taobao.com", "1111@qq.com");
        ApiInfo apiInfo= new ApiInfo("测试", "这是一个测试文档", "1.0", "http://www.taobao.com", DEFAULT_CONTACT, "心太入戏", "http://www.jd.com", new ArrayList<VendorExtension>());
        return apiInfo;
    }
}

3、开启swagger注解

主启动类

@EnableSwagger2 // 开启swagger注解
@SpringBootApplication
@MapperScan(basePackages = "com.zzs.mapper")  //为指定的包下的接口生成代理实现类
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootApplication.class, args);
    }

}

4、使用swagger注解

@Api  接口类的注解---接口类上 tag属性
@ApiOperation  接口方法的注解---接口方法上 value:
@ApiImplicitParams( 接口参数的说明
    {
      ApiImplicitParam() //单个参数的说明
    }
)

@ApiModel---- 实体类接口注解
@ApiModelProperty---->实体类属性的说明

5、测试

mapper

import com.zzs.entity.Student;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public interface StudentMapper {
    Student findById(Integer id);
    List<Student> findAll();
    int insert(@Param("name") String name,@Param("tid") Integer tid);

    int deleteById(Integer id);

    int updateById(@Param("name") String name,@Param("tid") Integer tid,@Param("id") Integer id);
}

controller

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zzs.entity.Student;
import com.zzs.mapper.StudentMapper;
import com.zzs.util.CommonResult;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class HelloController {
    @GetMapping("getInfo")
    @ApiOperation(value = "获取信息")
    public Map<String,Object> getInfo(){
        Map<String,Object> map = new HashMap();
        map.put("name","四脚吞金兽");
        map.put("age",1);
        return map;
    }

    @PostMapping("login")
    @ApiOperation(value = "登录接口")
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(value = "账号",name = "username",required = true),
                    @ApiImplicitParam(value = "密码",name = "password",required = true)
            }
    )
    public CommonResult login(String username,String password){
        return new CommonResult(2000,"登陆成功",null);
    }


    @Autowired
    StudentMapper studentMapper;

    @GetMapping("findById")
    @ApiOperation(value = "根据id查询")
    @ApiImplicitParam(value = "学生学号",name = "id",required = true,dataType = "int")
    public CommonResult findById(Integer id){
        Student byId = studentMapper.findById(id);
        System.out.println(studentMapper.findById(id));
        return new CommonResult(2000,"查询成功",byId);
    }

    @GetMapping("findAll")
    @ApiOperation(value = "查询所有并完成分页")
    public CommonResult findAll(){
        PageHelper.startPage(1,2);
        List<Student> list = studentMapper.findAll();
        PageInfo<Student> pageInfo = new PageInfo<>(list);
        System.out.println("当前页码"+pageInfo.getPageNum());
        System.out.println("总条数"+pageInfo.getTotal());
        System.out.println("每页数量"+pageInfo.getPageSize());
        return new CommonResult(2000,"查询成功",pageInfo);
    }

    @GetMapping("insert")
    @ApiOperation(value = "添加数据")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "学生姓名",name = "name",required = true),
            @ApiImplicitParam(value = "教师编号",name = "tid",required = true,dataType = "int")
    })
    public CommonResult insert(String name,Integer tid){

        int i = studentMapper.insert(name, tid);
        System.out.println(i);
        return new CommonResult(2000,"添加成功",null);
    }

    @GetMapping("deleteById")
    @ApiOperation(value = "根据id删除内容")
    @ApiImplicitParam(value = "学生编号",name = "id",required = true,dataType = "int")
    public CommonResult deleteById(Integer id){
        int i = studentMapper.deleteById(id);
        System.out.println(i);
        return new CommonResult(2000,"删除成功",null);
    }

    @GetMapping("updateById")
    @ApiOperation(value = "根据id更新数据")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "学生姓名",name = "name",required = true),
            @ApiImplicitParam(value = "教师编号",name = "tid",required = true,dataType = "int"),
            @ApiImplicitParam(value = "学生学号",name = "id",required = true,dataType = "int")
    })
    public CommonResult updateById(String name,Integer tid,Integer id){
        int i = studentMapper.updateById(name, tid, id);
        System.out.println(i);
        return new CommonResult(2000,"修改成功",null);
    }


}

5、查看API文档

第一种: http://localhost:8081/swagger-ui.html

第二种: http://localhost:8081/doc.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值