当前位置:   article > 正文

Springboot入门级教程详解_springboot教程

springboot教程

一.Springboot的实现

1.什么是Springboot

springboot可以帮你简化spring的搭建,并且快速创建一个spring的应用程序。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置

2.Springboot特点有哪些

(1)可以创建独立的Spring应用程序,并且基于其Maven或Gradle插件,可以创建可执行的JARs和WARs;
(2)内嵌Tomcat或Jetty等Servlet容器;
(3)提供自动配置的“starter”项目对象模型(POMS)以简化Maven配置;
(4)尽可能自动配置Spring容器;
(5)提供准备好的特性,如指标、健康检查和外部化配置;
(6)绝对没有代码生成,不需要XML配置。 

二.创建springboot工程

1.JDK必须为1.8以上

2.spring的jar必须5.0以上

3.maven必须3.3以

  

 创建一个controller类

 

1.介绍springboot中pom文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <!--parent: 继承
  6. 如果你的maven项目想成为springboot工程必须继承SpringBoot父依赖
  7. -->
  8. <parent>
  9. <groupId>org.springframework.boot</groupId>
  10. <artifactId>spring-boot-starter-parent</artifactId>
  11. <version>2.3.12.RELEASE</version>
  12. <relativePath/> <!-- lookup parent from repository -->
  13. </parent>
  14. <groupId>com.ykq</groupId>
  15. <artifactId>qy151-springboot</artifactId>
  16. <version>0.0.1-SNAPSHOT</version>
  17. <name>qy151-springboot</name>
  18. <description>Demo project for Spring Boot</description>
  19. <properties>
  20. <java.version>1.8</java.version>
  21. </properties>
  22. <dependencies>
  23. <!--web的启动依赖 把spring中常见的jar都集成到该依赖中,集成了springmvc的启动配置类 -->
  24. <dependency>
  25. <groupId>org.springframework.boot</groupId>
  26. <artifactId>spring-boot-starter-web</artifactId>
  27. </dependency>
  28. <dependency>
  29. <groupId>org.projectlombok</groupId>
  30. <artifactId>lombok</artifactId>
  31. <optional>true</optional>
  32. </dependency>
  33. <dependency>
  34. <groupId>org.springframework.boot</groupId>
  35. <artifactId>spring-boot-starter-test</artifactId>
  36. <scope>test</scope>
  37. </dependency>
  38. </dependencies>
  39. <build>
  40. <plugins>
  41. <plugin>
  42. <groupId>org.springframework.boot</groupId>
  43. <artifactId>spring-boot-maven-plugin</artifactId>
  44. <configuration>
  45. <excludes>
  46. <exclude>
  47. <groupId>org.projectlombok</groupId>
  48. <artifactId>lombok</artifactId>
  49. </exclude>
  50. </excludes>
  51. </configuration>
  52. </plugin>
  53. </plugins>
  54. </build>
  55. </project>

 

 默认springboot扫描的包为主启动类所在的包以及子包。

 2.springboot的配置文件

有两种格式的配置文件:

第一种: properties属性文件

​
# 修改springboot中tomcat端口号.
server.port=8888

第二种: yml文件

server:
  port: 9090

不管是哪种,他们的名字必须以application开始。

如果两个配置文件同时存在,而且有些内容一样。按照properties的优先级高。如果有些不一样,两个配置文件不一样的会合并在一起。

3.读取springboot配置文件中的内容

OSS文件上传

密钥和bucket名称等---密钥和bucket都写死在java代码中。如果后期修改密钥和bucket的值,你必须修改源码代码。 我们要写在配置文件。然后通过代码在读取配置文件中的密钥和bucket.

如何读取springboot配置文件的内容呢?

通过@PropertiesConfiguration或者@Value注解。

@PropertiesConfiguration该注解使用在类上。  

(1) 创建实体类

  1. @Data
  2. @Component //该类对象的创建和销毁都有spring容器来管理
  3. @ConfigurationProperties(prefix = "student") //读取springboot中的配置内容
  4. public class Student {
  5. private String name;
  6. private Integer age;
  7. private String[] hobby;
  8. private Map<String,Object> map;
  9. }

(2) 给application.properties配置信息

  1. #配置数据
  2. student.name=jk
  3. student.age = 15
  4. student.hobby[0] = sing
  5. student.hobby[1] = swimming
  6. student.map.claszz = aaa
  7. student.map.stusex = f

 (3)读取配置内容 

  1. package com.wt.springboot02.com.wt.controller;
  2. import com.wt.springboot02.com.wt.entity.Student;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.beans.factory.annotation.Value;
  5. import org.springframework.web.bind.annotation.RequestMapping;
  6. import org.springframework.web.bind.annotation.RestController;
  7. import java.util.HashMap;
  8. import java.util.Map;
  9. /**
  10. * @Author wt
  11. * @Date 2022/7/21 19:17
  12. * @PackageName:com.wt.springboot02.com.wt.controller
  13. * @ClassName: HelloController
  14. * @Description: TODO
  15. * @Version 1.0
  16. */
  17. @RestController
  18. public class HelloController {
  19. //通过value获取指定内容,但只能获取基本数据类型和String
  20. @Value("${student.name}")
  21. private String stuName;
  22. @Autowired
  23. private Student student;
  24. @RequestMapping("stu")
  25. public Student fun(){
  26. System.out.println(stuName);
  27. return student;
  28. }
  29. }



 

4.profiles文件的介绍

思考: 我们在实际开发中,环境有哪些?

开发环境---->测试环境---->线上环境 由于环境的不同,那么就会有不同的配置内容。

难道我们不断的修改配置内容。----不会

实际工作中,针对不同的环境配置不同的配置文件,然后再总的配置文件中激活相应的配置文件。

 

5.Springboot注册web三大组件

什么是web的三个组件?

Servlet和Filter以及Linstener监听器。

为什么要注册这三个组件呢?

因为后面springboot有可能要集成第三方框架,而第三方框架的底层可能就依赖于过滤器或者servlet.

如何注册呢?

思考: 早期:

<1>Servlet类

<2>注册到Tomcat容器web.xml

(1)Servlet类 

早期注册 

 <servlet>
    <servlet-name></servlet-name>
    <servlet-class>Servlet类</servlet-class>
</servlet>
<servlet-mapping>
     <servlet-name></servlet-name>
     </url-parterrn>/</url-parterrn>
</servlet-mapping>

现在:都没有web.xml

创建一个配置类:

 

  1. package com.wt.springboot02.com.wt.config;
  2. import com.wt.springboot02.com.wt.servlet.MyFilter;
  3. import com.wt.springboot02.com.wt.servlet.MyServlet;
  4. import org.springframework.boot.web.servlet.FilterRegistrationBean;
  5. import org.springframework.boot.web.servlet.ServletRegistrationBean;
  6. import org.springframework.context.annotation.Bean;
  7. import org.springframework.context.annotation.Configuration;
  8. import javax.servlet.Filter;
  9. import javax.servlet.Servlet;
  10. /**
  11. * @Author wt
  12. * @Date 2022/7/21 20:34
  13. * @PackageName:com.wt.springboot02.com.wt.config
  14. * @ClassName: MyConfig
  15. * @Description: TODO
  16. * @Version 1.0
  17. */
  18. @Configuration //该类为配置类xml文件
  19. public class MyConfig {
  20. @Bean //理解为配置文件中的Bean
  21. public ServletRegistrationBean<Servlet> registrationBean(){
  22. //创建一个Servlet注册器.
  23. ServletRegistrationBean<Servlet> registrationBean = new ServletRegistrationBean<>();
  24. registrationBean.setName("myServlet");
  25. registrationBean.setServlet(new MyServlet());
  26. registrationBean.addUrlMappings("/my");
  27. return registrationBean;
  28. }
  29. }

 (2) 过滤器

以前如何注册过滤器: web.xml

​ <filter>

​ <filter-name></filter-name>

​ <filter-class></filter-class>

​ </filter>

​ <filter-mapping>

​ <filter-name></filter-name>

​ <url-partter></url-partter>

​ </filter-mapping>

 

  1. package com.wt.springboot02.com.wt.config;
  2. import com.wt.springboot02.com.wt.servlet.MyFilter;
  3. import com.wt.springboot02.com.wt.servlet.MyServlet;
  4. import org.springframework.boot.web.servlet.FilterRegistrationBean;
  5. import org.springframework.boot.web.servlet.ServletRegistrationBean;
  6. import org.springframework.context.annotation.Bean;
  7. import org.springframework.context.annotation.Configuration;
  8. import javax.servlet.Filter;
  9. import javax.servlet.Servlet;
  10. @Configuration //该类为配置类xml文件
  11. public class MyConfig {
  12. @Bean
  13. public FilterRegistrationBean<Filter> filterFilterRegistrationBean(){
  14. FilterRegistrationBean<Filter> filterFilterRegistrationBean = new FilterRegistrationBean<>();
  15. filterFilterRegistrationBean.setName("myfilter");
  16. filterFilterRegistrationBean.setFilter(new MyFilter());
  17. filterFilterRegistrationBean.addUrlPatterns("/*");
  18. return filterFilterRegistrationBean;
  19. }
  20. }

三.Springboot的整合 

1.springboot自动装配原理

什么是自动装配?

无需手动加载某些配置,而由Springboot自动加载进来。

譬如: 自己加载DispatcherServlet.

如何完成自动装配?

 

 

 

 为什么总的自动装配类由127个。因为这些自动装配类都在某个文件中写死了。

 

 看DispatcherServlet如何完成自动装配。

2.springboot整合数据源

a.默认数据配置

 数据源: 指的是数据源。即是: springboot框架连接数据库。

 (1)引入依赖

  1. <!--加入数据源的启动依赖: springboot启动时会加载对应的自动装配类。-->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-jdbc</artifactId>
  5. </dependency>
  6. <dependency>
  7. <groupId>mysql</groupId>
  8. <artifactId>mysql-connector-java</artifactId>
  9. </dependency>

(2)配置数据源信息---application.properties

  1. # 配置数据源
  2. spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
  3. spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=Asia/Shanghai
  4. spring.datasource.username=root
  5. spring.datasource.password=root

(3)测试  

  1. package com.wt.springboot03;
  2. import com.github.pagehelper.PageHelper;
  3. import com.github.pagehelper.PageInfo;
  4. import com.wt.springboot03.dao.DeptMapper;
  5. import com.wt.springboot03.entity.Dept;
  6. import org.apache.ibatis.annotations.Mapper;
  7. import org.junit.jupiter.api.Test;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.boot.test.context.SpringBootTest;
  10. import javax.sql.DataSource;
  11. import java.sql.SQLException;
  12. import java.util.List;
  13. //添加主体类注解
  14. @SpringBootTest(classes = Springboot03Application.class)
  15. class Springboot03ApplicationTests {
  16. @Autowired
  17. private DataSource dataSource;
  18. @Test
  19. public void test01() throws SQLException {
  20. //System.out.println(dataSource);
  21. System.out.println(dataSource.getConnection());
  22. }
  23. }

上面默认这个数据源使用的连接池Hikari。如果不想使用默认的连接池,我们可以引入第三方的连接池。

b.集成druid数据源

(1)引入依赖

  1. <!--引入数据库连接池druid-->
  2. <dependency>
  3. <groupId>com.alibaba</groupId>
  4. <artifactId>druid-spring-boot-starter</artifactId>
  5. <version>1.2.8</version>
  6. </dependency>

(2)配置数据源信息---application.properties  

  1. spring.datasource.druid.url=jdbc:mysql://localhost:3306/mydb?serverTimezone=Asia/Shanghai
  2. spring.datasource.druid.driver-class-name=com.mysql.cj.jdbc.Driver
  3. spring.datasource.druid.username=root
  4. spring.datasource.druid.password=root
  5. #初始化的个数
  6. spring.datasource.druid.initial-size=5
  7. # 最大活跃数
  8. spring.datasource.druid.max-active=10
  9. # 最大等待时间
  10. spring.datasource.druid.max-wait=3000
  11. # 最小的闲置个数
  12. spring.datasource.druid.min-idle=5

(3)测试  

  1. @SpringBootTest(classes = Springboot01Lx02Application.class)
  2. class Springboot01Lx02ApplicationTests {
  3. @Autowired
  4. private DataSource dataSource;
  5. @Test
  6. public void test01() throws SQLException {
  7. //验证了springboot可以帮你完成数据源的自动装配功能
  8. System.out.println(dataSource.getConnection());
  9. }
  10. }

3.springboot整合mybatis

(1)引入mybatis启动依赖类

  1. <!--引入mybatis的启动依赖-->
  2. <dependency>
  3. <groupId>org.mybatis.spring.boot</groupId>
  4. <artifactId>mybatis-spring-boot-starter</artifactId>
  5. <version>2.2.2</version>
  6. </dependency>

(2) 修改配置文件

在application文件中进行配置

  1. #指定映射文件的路径
  2. mybatis.mapper-locations=classpath:mapper/*.xml

 

(4)测试  

  1. @RestController
  2. public class DeptController {
  3. @GetMapping("hello")
  4. public void fun(){
  5. System.out.println("111");
  6. }
  7. public CommonResult login(String name, String password){
  8. return new CommonResult(2000,"登录成功",null);
  9. }
  10. }

4.springboot整合PageHelper分页插件

(1)引入依赖

  1. <!--pageHelper的启动依赖 自动装配拦截器-->
  2. <dependency>
  3. <groupId>com.github.pagehelper</groupId>
  4. <artifactId>pagehelper-spring-boot-starter</artifactId>
  5. <version>1.4.2</version>
  6. </dependency>

(2)测试:

  1. @Test
  2. public void test03(){
  3. PageHelper.startPage(1,3);
  4. List<Dept> all = deptMapper.findAll();
  5. PageInfo<Dept> pageInfo = new PageInfo<>(all);
  6. System.out.println(pageInfo);
  7. System.out.println("当前页码"+pageInfo.getPageNum());
  8. System.out.println("总页码:"+pageInfo.getPages());
  9. System.out.println("总条数:"+pageInfo.getTotal());
  10. System.out.println("当前页码:"+pageInfo.getList());
  11. }

5.springboot整合swagger2

什么是swagger2

它是一个接口文档----用来前后端分离的一款文档。

(1)引入swagger依赖

  1. <dependency>
  2. <groupId>com.spring4all</groupId>
  3. <artifactId>swagger-spring-boot-starter</artifactId>
  4. <version>1.9.1.RELEASE</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>com.github.xiaoymin</groupId>
  8. <artifactId>swagger-bootstrap-ui</artifactId>
  9. <version>1.7.8</version>
  10. </dependency>

(2)创建swagger配置类

  1. package com.wt.springboot03.config;
  2. import io.swagger.annotations.Api;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. import springfox.documentation.builders.RequestHandlerSelectors;
  6. import springfox.documentation.service.ApiInfo;
  7. import springfox.documentation.service.Contact;
  8. import springfox.documentation.service.VendorExtension;
  9. import springfox.documentation.spi.DocumentationType;
  10. import springfox.documentation.spring.web.plugins.Docket;
  11. import java.util.ArrayList;
  12. /**
  13. * @Author wt
  14. * @Date 2022/7/22 19:52
  15. * @PackageName:com.wt.springboot03.config
  16. * @ClassName: MySwagger
  17. * @Description: TODO
  18. * @Version 1.0
  19. */
  20. @Configuration
  21. public class MySwagger {
  22. @Bean //swagger中所有的功能都封装再Docket类中
  23. public Docket docket(){
  24. Docket docket = new Docket(DocumentationType.SWAGGER_2)
  25. .apiInfo(apiInfo())
  26. .select()
  27. .apis(RequestHandlerSelectors.basePackage("com.wt.springboot03.controller")) //为指定包下的路径生成接口
  28. .build();
  29. return docket;
  30. }
  31. //定义自己的接口文档信息
  32. private ApiInfo apiInfo(){
  33. Contact DEFAULT_CONTACT = new Contact("", "", "");
  34. ApiInfo apiInfo = new ApiInfo("子非鱼呀", "https:www.zfy.com", "b.2.0", "urn:tos",
  35. DEFAULT_CONTACT, "子非鱼的小屋", "http:www.baidu.com", new ArrayList<VendorExtension>());
  36. return apiInfo;
  37. }
  38. }

(3)开启swagger注解

  (4)使用swagger注解

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

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

 实体返回类上的注解

 

(5)访问  

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

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

  (6) 使用springboot-mybatis整合进行简单的crud操作

  1. package com.wt.springboot03.controller;
  2. import com.github.pagehelper.PageHelper;
  3. import com.github.pagehelper.PageInfo;
  4. import com.wt.springboot03.dao.DeptMapper;
  5. import com.wt.springboot03.dao.UserMapper;
  6. import com.wt.springboot03.entity.Dept;
  7. import com.wt.springboot03.entity.User;
  8. import com.wt.springboot03.service.UserService;
  9. import com.wt.springboot03.util.CommonResult;
  10. import io.swagger.annotations.Api;
  11. import io.swagger.annotations.ApiImplicitParam;
  12. import io.swagger.annotations.ApiImplicitParams;
  13. import io.swagger.annotations.ApiOperation;
  14. import org.springframework.beans.factory.annotation.Autowired;
  15. import org.springframework.beans.factory.annotation.Value;
  16. import org.springframework.web.bind.annotation.GetMapping;
  17. import org.springframework.web.bind.annotation.RequestMapping;
  18. import org.springframework.web.bind.annotation.RestController;
  19. import java.util.List;
  20. /**
  21. * @Author wt
  22. * @Date 2022/7/22 21:00
  23. * @PackageName:com.wt.springboot03.controller
  24. * @ClassName: UserController
  25. * @Description: TODO
  26. * @Version 1.0
  27. */
  28. @RestController
  29. @Api(tags = "tbl_user表的crud操作接口") //类api注解
  30. public class UserController {
  31. @Autowired
  32. private UserMapper userMapper;
  33. //查询所有
  34. @GetMapping("findAll")
  35. @ApiOperation(value = "查询所有")
  36. public CommonResult findAll(){
  37. PageHelper.startPage(1,3);
  38. List<User> all = userMapper.findAll();
  39. PageInfo<User> pageInfo = new PageInfo<>(all);
  40. if (all!=null){
  41. return new CommonResult(2000,"查询成功",pageInfo);
  42. }
  43. return new CommonResult(5000,"查询失败",null);
  44. }
  45. //添加
  46. @GetMapping("insert")
  47. @ApiOperation(value = "添加一条数据")
  48. @ApiImplicitParams(
  49. {
  50. @ApiImplicitParam(value = "添加新的账号",name = "username",required = true),
  51. @ApiImplicitParam(value = "添加密码",name = "password",required = true)
  52. }
  53. )
  54. public CommonResult insert(String username,String password){
  55. int i = userMapper.insertUser(username,password);
  56. if (i>0){
  57. return new CommonResult(2000,"添加成功",null);
  58. }
  59. return new CommonResult(5000,"添加失败",null);
  60. }
  61. //修改
  62. @GetMapping("update")
  63. @ApiOperation("修改接口")
  64. @ApiImplicitParams(
  65. {
  66. @ApiImplicitParam(value = "要修改的数据id",name = "id",required = true),
  67. @ApiImplicitParam(value = "修改数据username",name = "username",required = true),
  68. @ApiImplicitParam(value = "要修改数据password",name = "password",required = true)
  69. }
  70. )
  71. public CommonResult update(Integer id,String username,String password){
  72. int i = userMapper.updateUser(id,username,password);
  73. if (i>0){
  74. return new CommonResult(2000,"修改成功",null);
  75. }
  76. return new CommonResult(5000,"修改失败",null);
  77. }
  78. @GetMapping("delete")
  79. @ApiOperation("删除接口,根据id删除单条数据")
  80. @ApiImplicitParam(value = "指定数据id",name = "id",required = true)
  81. //删除
  82. public CommonResult delete(Integer id){
  83. int i = userMapper.deleteUser(id);
  84. if (i>0){
  85. return new CommonResult(2000,"删除成功",null);
  86. }
  87. return new CommonResult(5000,"删除失败",null);
  88. }
  89. }

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/article/detail/57648
推荐阅读
相关标签
  

闽ICP备14008679号