SpringBoot学习笔记

文章目录

SpringBoot入门

(转)参考

java元注解https://blog.csdn.net/pengjunlee/article/details/79683621

SpringBoot启动类原理:https://blog.csdn.net/zhoushimiao1990/article/details/90258014

@SpringBootApplication注解:https://www.cnblogs.com/MaxElephant/p/8108140.html
@SpringBootApplication注解 详细的:https://blog.csdn.net/qq_28289405/article/details/81302498

Springboot 快速入门https://blog.csdn.net/hzygcs/article/details/85230526

springboot注解(发则韩)https://blog.csdn.net/weixin_43575868/article/details/108844002

springboot面试题https://blog.csdn.net/ThinkWon/article/details/104397299

一、SpringBoot介绍

随着互联网的兴起,Spring一直占据着Java领域轻量级开发框架的王者地位。
但是Spring框架发展十几年来,框架越来越庞大、配置项越来越多,造成开发使用起来非常复杂。
为此Spring官方推出了SpringBoot这个项目,其设计初衷就是为了简单、快速的开发Spring应用

什么是SpringBoot?
Spring Boot是一种 简化原有Spring应用繁杂配置的微框架 。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。使开发者从繁杂的各种配置文件中解脱出来。
通过Spring Boot能够很简单、很快速构建一个优秀的、产品级的Spring基础应用。

SpringBoot特点:
1.可快速构建独立的Spring应用
2.提供场景启动器简化构建配置
3.基础Spring配置自动实现,无需繁琐的xml配置文件
4.整合常用Spring和第三方依赖库
5.直接嵌入Web应用服务器(无需部署WAR包)
6.微服务的入门框架

二、快速入门:创建第一个SpringBoot工程

(转)SpringBoot各种注解

1、创建springboot工程

1、点击File—>New—>Project…
注意Artifact不要出现大写、特殊字符.
在这里插入图片描述
在这里插入图片描述

2、选择SpringBoot版本,选择项目需要依赖的相关骨架包

springboot版本介绍与选择https://www.cnblogs.com/chsoul/p/12545137.html
在这里插入图片描述

  • Alpha:不建议使用,主要是以实现软件功能为主,通常只在软件开发者内部交流,Bug较多;
  • Beta:该版本相对于α版已有了很大的改进,消除了严重的错误,但还是存在着一些缺陷,需要经过多次测试来进一步消除;
  • GA:General Availability,正式版本,官方推荐使用此版本,在国外都是用GA来说明release版本;
  • M:又叫里程碑版本,表示该版本较之前版本有功能上的重大更新;
  • PRE(不建议使用):预览版,内部测试版,主要是给开发人员和测试人员测试和找BUG用的;
  • Release:最终版本,Release不会以单词形式出现在软件封面上,取而代之的是符号®;
  • RC:该版本已经相当成熟了,基本上不存在导致错误的BUG,与即将发行的正式版相差无几;
  • SNAPSHOT:快照版,可以稳定使用,且仍在继续改进版本。

在这里插入图片描述

3、设置项目保存目录:
在这里插入图片描述

4、项目创建完成,工程主界面如下:
在这里插入图片描述

2、项目说明

在这里插入图片描述

  1. 默认有个项目名+Application类,里面是spring boot的载入函数。(如项目名为demospringboot,载入函数类就是:DemoSpringbootApplication
    package com.example.demospringboot;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class DemoSpringbootApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(DemoSpringbootApplication.class, args);
        }
    
    }	
    
  2. resource目录下有个application.properties文件,这个是Spring boot的配置文件,可以改成application.yml配置文件
  3. test目录下有个测试类,这个是spring boot的单元测试
  4. pom.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    
    继承了 spring-boot-starter-parent
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.10.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    
    <groupId>com.example</groupId>
    <artifactId>demo-springboot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo-springboot</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

		web的springboot启动器 依赖(web项目依赖)
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>


		springboot的单元测试依赖
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
        	maven编译插件
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

注意观察
一个继承spring-boot-starter-parent,
两个依赖,
spring-boot-starter-web web项目依赖必须,
spring-boot-starter-test spring boot项目单元测试依赖

注意,阿里云maven镜像,在这可能会有找不到最新Springboot相关包的问题,可以把加速镜像指向华为云:

<mirror>
    <id>huaweicloud</id>
    <mirrorOf>*</mirrorOf>
    <url>https://mirrors.huaweicloud.com/repository/maven/</url>
</mirror>

3 启动项目

通过spring boot的启动类,这里是DemoSpringbootApplication,选中类,启动 启动类的main方法

在控制台出现如下输出:
在这里插入图片描述

找到如下文字,表明SpringBoot已经成功启动:
在这里插入图片描述

打开浏览器,输入地址:http://localhost:8080 ,出现如下画面,因为我们只有一个tomcat,什么都没有配置,所以是404页面。
在这里插入图片描述

7、编写HelloController

package com.example.demospringboot.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @RequestMapping(value="/hello",method = RequestMethod.GET)
    public String hello(){
        return "hello spring boot";
    }
}

注意:HelloController所在包,必须在启动类的包,或者子包下面

重启应用
访问http://localhost:8080/hello
在这里插入图片描述

三、SpringBoot Web扩展

lombok参考

Lombok使用

1、导入依赖库

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.6</version>
</dependency>

2、安装 Lombok插件
在这里插入图片描述

1、SpringBoot json支持

(1)、创建实体bean Car
在实体bean使用lombok的注解

  • @Data // @Data 包含了 @ToString、@EqualsAndHashCode、@Getter / @Setter和@RequiredArgsConstructor的功能
  • @AllArgsConstructor //所有参数的有参数构造函数
  • @NoArgsConstructor //无参数构造函数
package com.example.demospringboot.po;

import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Date;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Car {

    private Integer id;
    private String name;
    private Float price;

    // 将Date格式转为string类型,用作前端显示
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
    private Date createDate;
}

(2)、创建Controller CarController

package com.example.demospringboot.controller;

import com.example.demospringboot.po.Car;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/car")
public class CarController {

    @RequestMapping("/findOne")
    public Car findOne(){
        return new Car(1,"张三", 100.0F,new Date());
    }

    @RequestMapping("/findAll")
    public List<Car> getAll(){
        List<Car> list=new ArrayList<>();
        Car car1 = new Car(1, "toyo", 1999.99F,new Date());
        Car car2= new Car(2, "dazhong", 2999.99F,new Date());
        Car car3 = new Car(3, "fengtian", 3999.99F,new Date());
        Car car4 = new Car(4, "benchi", 4999.99F,new Date());
        list.add(car1);
        list.add(car2);
        list.add(car3);
        list.add(car4);

        return list;

    }

}

(3)、测试获取单个对象json
请求地址:http://localhost:8080/car/findOne
在这里插入图片描述

(5)、测试获取集合多个对象json
请求地址:http://localhost:8080/car/findAll
在这里插入图片描述

2、SpringBoot 静态资源

2.1、默认静态资源映射

Spring Boot 对静态资源映射提供了默认配置
Spring Boot 默认将/**所有访问映射到以下目录:

classpath:/static
classpath:/public
classpath:/resources
classpath:/META-INF/resources

如:在resources目录下新建 public、resources、static 三个目录,并分别放入 a.jpg b.jpg c.jpg 图片

浏览器分别访问:
http://localhost:8080/a.jpg
http://localhost:8080/b.jpg
http://localhost:8080/c.jpg
均能正常访问相应的图片资源。

注意:添加图片,或修改图片后,可能需要mvn-clean
静态资源的访问顺序:META-INF/resources > resources > static > public

2.2 自定义静态资源访问

试想这样一种情况:一个网站有文件上传文件的功能,如果被上传的文件放在上述的那些文件夹中会有怎样的后果?
网站数据与程序代码不能有效分离;
当项目被打包成一个.jar文件部署时,再将上传的文件放到这个.jar文件中是有多么低的效率;
网站数据的备份将会很痛苦。
此时可能最佳的解决办法是将静态资源路径设置到磁盘的基本个目录。

第一种方式:配置类

1、配置类

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
  
   // 添加资源处理器 ,处理静态资源的映射路径
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //将所有D:\\springboot\\pic\\ 访问都映射到/myPic/** 路径下
        registry.addResourceHandler("/myPic/**").addResourceLocations("file:D:\\springboot\\pic\\");
    }
}

上面的意思就是:将所有D:/springboot/pic/ 访问都映射到**/myPic/**** 路径下

方法2:配置(映射导项目里的template文件夹

@Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/template/**").addResourceLocations("classpath:template/");
    }

在这里插入图片描述

2、重启项目
例如,在D:/springboot/pic/中有一张logo.jpg图片
在浏览器输入:http://localhost:8080/myPic/logo.jpg即可访问。

第二种方式:配置application.properties

首先,我们配置application.properties

web.upload-path=D:/springboot/pic/
spring.mvc.static-path-pattern=/**
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,\
  classpath:/static/,classpath:/public/,file:${web.upload-path}

注意:
web.upload-path:这个属于自定义的属性,指定了一个路径,注意要以/结尾

spring.mvc.static-path-pattern=/**:表示所有的访问都经过静态资源路径;

spring.resources.static-locations:在这里 配置静态资源路径,前面说了这里的配置是覆盖默认配置,所以需要将默认的也加上否则static、public等这些路径将不能被当作静态资源路径,在这个最末尾的file:${web.upload-path}之所有要加file: 是因为指定的是一个具体的硬盘路径,其他的使用classpath指的是系统环境变量。

然后,重启项目
例如,在D:/springboot/pic/中有一张8.png图片
在浏览器输入:http://localhost:8080/8.png 即可访问。

3、WebJars

在SpringBoot中,允许我们直接访问WEB-INF/lib下的jar包中的 /META-INF/resources 目录资源
WEB-INF/lib/{*.jar}/META-INF/resources 下的资源可以直接访问

WebJars也是利用了此功能,将所有前端的静态文件打包成一个jar包,这样对于引用放而言,和普通的jar引入是一样的,还能很好的对前端静态资源进行管理。

WebJars是将web前端资源(如jQuery & Bootstrap)打成jar包文件。借助版本管理工具(Maven、gradle等)进行版本管理,保证这些Web资源版本唯一性。避免了文件混乱、版本不一致等问题。

1 WebJar结构

开始使用前,我们看下Jquery的webjars,借此来了解下webjars包的目录结构。以下是基于jquery-3.3.1.jar:

META-INF
    └─maven
        └─org.webjars.bower
            └─jquery
                └─pom.properties
                └─pom.xml
    └─resources
        └─webjars
            └─jquery
                └─3.3.1
                       └─(静态文件及源码)

在这里插入图片描述

jquery-3.3.1目录结构
所以可以看出,静态文件存放规则META-INF/resources/webjars/${name}/${version}

2 WebJars实践

接下来我们以一个简单的示例,对webjars进行简单的实践下。

1、按照webjars的静态文件存放规格 META-INF/resources/webjars/${name}/${version}, 创建目录,模拟webjars,同时为了演示效果,拷贝一个图片到此目录下。

在这里插入图片描述

2、编写一个简单的html页面,放在src/main/resources/static下(当然也可以直接放在webjar下了,只需要后面加个映射关系即可),内容如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello,WebJars</title>
</head>
<body>
  <h1>Hello,WebJars</h1>
  <img alt="" src="webjars/demo/0.0.1/aaa.jpg">
</body>
</html>

3、编写配置类,添加一个资源映射关系.可以不写,因为springboot默认的四个资源路径里面就包含了/META-INF/resources/了

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {        
    	//配置映射关系  
    	registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

4、编写控制层,返回此页面地址。

/** webjar示例
 * @author sunny
 * */
@Controller
public class WebJarsDemoController {     
    @GetMapping("/")
    public String index() {
        return "index.html";
    } 
}

5、启动应用,访问地址即可:
在这里插入图片描述

可以看见图片已经正确显示出来了。

6、现在将META-INF下打成一个jar,然后加该jar的依赖

  1. 这里直接创建一个新的工程,存在静态资源信息 (将demo-webjars中META-INF/resources/webjars下的 资源 拷贝到新工程) ,工程结果如下:
    在这里插入图片描述

  2. 然后对应的pom配置文件加入一个资源拷贝动作:

    打包时,将resources下的目录,复制到/META-INF/resources/webjars目录下

    因为jar包只有/META-INF/resources/目录可以被访问,为了遵守静态文件存放规则META-INF/resources/webjars/${name}/${version}

    这样的话,这个工程的jar包,就可以完全代替 上面,demo-webjars中的 META-INF/resources/webjars/*

    <build>
        <resources>
    		从本工程的基础路径resources,复制到输出路径的/META-INF/resources/webjars 。
    		即打包时,将resources目录下的资源复制到/META-INF/resources/webjars/目录下
            <resource>
                <directory>${project.basedir}/src/main/resources</directory>
                <targetPath>${project.build.outputDirectory}/META-INF/resources/webjars</targetPath>
            </resource>
        </resources>
    </build>
    

利用maven打包后,就可以看见jar包目录结构了:
在这里插入图片描述

7、然后我们删除了我们原先的资源文件或者图片重命名下,并引入依赖:

	 <!-- 添加自定义 webjar 的依赖 -->
        <dependency>
            <groupId>com.example</groupId>
            <artifactId>demo-mywebjar</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>

最后重新启动应用,再次访问下,依旧是正常显示的!

3 WebJars常用引用
Jquery:
<dependency>
	<groupId>org.webjars</groupId>
	<artifactId>jquery</artifactId>
	<version>3.3.1-1</version>
</dependency>

Bootstrap:
<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>bootstrap</artifactId>
    <version>4.2.1</version>
</dependency>

WebJars查询:https://www.webjars.org/all

四、SpringBoot属性配置

Spring Boot并不真正是所谓的『零配置』,他的理念是“约定优于配置”采用了一些默认的习惯性配置,让你无需手动进行配置,从而让你的项目快速运行起来。所以要想玩转Spring Boot,了解这些默认配置还是必不可少的。

1、项目默认属性配置文件所在位置及配置实例

创建Spring Boot项目时,会默认生成一个全局配置文件application.properties(可以修改后缀为.yml),在src/main/resources目录下或者类路径的/config下。我们可以通过修改该配置文件来对一些默认配置的配置值进行修改。
在这里插入图片描述

【修改默认配置】

  • 1、spring boot 开发web应用的时候,默认tomcat的启动端口为8080,如果需要修改默认的端口,则需要在application.yml添加以下记录:

    server:
      port: 8888
    

    重启项目,启动日志可以看到:Tomcat started on port(s): 8888 (http) 启动端口为8888,浏览器中访问 http://localhost:8888 能正常访问。

  • 2、spring boot 开发web应用的时候,访问路径为/,如果需要修改访问路径,则需要在application.yml添加以下记录:

    server:
      port: 8888
      servlet:
        context-path: /java001
    

    重启项目,启动日志就可以看到:Tomcat started on port(s): 8888 (http) with context path ‘/java001’,浏览器中访问 http://localhost:8888/java001 能正常访问。

2、自定义属性及读取

我们可以在application.yml文件中,配置一些常量或者其他参数配置。通过Spring的@Value(“${属性名}”)注解读取

(1)、在application.yml定义几个常量:

my_ip:
         1.1.1.1
my_port:
           9999

(2)、编写Controller类读取自定义属性

package com.my.demo.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloConfigController {
@Value("${my_ip}")	
private String my_ip;

@Value("${my_port}")
private String my_port;

@GetMapping("/getvalue")
public String getValue() {
	return "ip:"+my_ip+" port:"+my_port;
}
}

访问http://localhost:8888/java001/getvalue
显示结果如下:
在这里插入图片描述

3、实体类属性赋值

当属性参数变多的时候,我们习惯创建一个实体,用实体来统一接收赋值这些属性。
(1)、定义配置文件

userbody:
  name: 张三
  password: 123456
  birthday: 1992.10.28
  mobile: 13802789765
  address: 北京市朝阳区

(2)、创建实体类

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationProperties;
@Data 
@AllArgsConstructor 
@NoArgsConstructor  
@ConfigurationProperties(prefix="userbody")
public class UserBody {
	 private String name;
	    private String password;
	    private String birthday;
	    private String mobile;
	    private String address;
}

需要在实体类上增加注解@ConfigurationProperties,并指定prefix前缀 。 加了这个前缀,取值时就不用每个属性前面设置 @Value("${userbody.*}")

注意:prefix前缀需要与properties文件中的前缀一致。
在这里插入图片描述
在这里插入图片描述

(3)、编写Controller调用属性bean


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.my.demo.bean.UserBody;

@RestController
@EnableConfigurationProperties({UserBody.class})
public class HelloControllerBean {
	@Autowired
    UserBody userbody;
    @GetMapping("/getUser")
    public String getUser(){
        return userbody.toString();
    }
}

EnableConfigurationProperties注解需要加在 调用类 或者加在启动类SpringbootSimpleApplication上。

当@EnableConfigurationProperties注解应用到你的@Configuration时, 任何被@ConfigurationProperties注解的beans将自动被Environment属性配置(注入)。

访问地址:http://localhost:8888/java001/getUser

4、自定义配置文件

application.yml系统默认的配置文件,当然我们也可以创建自定义配置文件,在路径src/main/resources下面创建文件test.properties

注意:spring boot 1.5版本后 @PropertySource注解 就不能加载自定义的yml配置文件了

(1)、定义test.properties

testuser.name = "zhangsan"
testuser.password = "123"
testuser.birthday = "1978.10.28"

(2)、将配置赋值到javabean



import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration
@PropertySource("classpath:test.properties")
@ConfigurationProperties(prefix = "testuser")
public class TestUser {
	private String name;
    private String password;
    private String birthday;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getBirthday() {
		return birthday;
	}
	public void setBirthday(String birthday) {
		this.birthday = birthday;
	}
	@Override
	public String toString() {
		return "testuser [name=" + name + ", password=" + password + ", birthday=" + birthday + "]";
	}
    
}
  1. @Configuration 注解包含@Component注解

  2. @ConfigurationProperties
    设定前缀,与属性文件中的前缀保持一致,可以被@EnableConfigurationProperties注解注入

  3. 1.5版本后 需要通过 @PropertySource(“classpath:test.properties”) 指定配置文件

(3)、Controller 读取配置


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.springboot.demo.bean.TestUser;
import com.springboot.demo.bean.UserBody;

@RestController
@EnableConfigurationProperties({UserBody.class,TestUser.class})
public class HelloControllerBean {
	@Autowired
    UserBody userbody;
	
	@Autowired
	TestUser testUser;

    @GetMapping("/getUser")
    public String getUser(){
        return userbody.toString();
    }
    
    @GetMapping("/gettestuser")
    public String gettestUser() {
    	return testUser.toString();
    }
}

访问地址:http://localhost:8888/java001/gettestuser

5、多环境配置文件

使用多个yml配置文件进行配置属性文件

可以使用多个yml来配置属性,将于环境无关的属性放置到application.yml文件里面;
通过与配置文件相同的命名规范创建application-{profile}.yml文件 存放不同环境特有的配置,

例如: application-test.yml 存放测试环境特有的配置属性,application-prod.yml 存放生产环境特有的配置属性。

通过这种形式来配置多个环境的属性文件,在application.yml文件里面 spring.profiles.active=xxx指定加载不同环境的配置, 如果不指定,则默认只使用application.yml属性文件,不会加载其他的profiles的配置

(1)、创建 application-dev.yml

server:
  port: 8003
  servlet:
    context-path: /java003

(2)、创建 application-test.yml

server:
  port: 8001
  servlet:
    context-path: /java001

(3)、创建 application-prod.yml

server:
  port: 8002
  servlet:
    context-path: /java002

(4)、修改application.yml

spring:
   profiles:
    active: test

通过设置,active: 的值对应不同的{profile}就可以使对应的配置文件生效。

6、application.yml和bootstrap.yml

在这里插入图片描述
在这里插入图片描述

链接:https://www.jianshu.com/p/512c523724b7
来源:简书

五、SpringBoot构建RESTful API

1、RESTful介绍

RESTful是一种软件架构风格
REST就是指对同一个URI的资源的不同请求方式(GET,POST,PUT,DELETE)(表述)下的做出的不同的操作(查,增,改,删),改变的是资源的状态,即表述性状态转移。 一个符合REST风格的URI就可以称之一个RESTful的接口

2、RESTful接口设计

在此我们以用户数据的基本操作来进行接口设计

HTTP协议请求方法SpringBoot注解URL功能说明
POST@PostMapping/user/创建一个用户
GET@GetMapping/user/查询用户列表
GET@GetMapping/user/id根据id查询一个用户
PUT@PutMapping/user/id根据id更新一个用户
DELETE@DeleteMapping/user/id根据id删除一个用户

3、用户实体bean创建

package com.restful.po;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private Long id;
    private String name;
    private Integer age;  
}

4、创建Controller UserController

Collections.synchronizedList使用用法:https://blog.csdn.net/LilllS/article/details/83417333

package com.restful.controllerold;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.restful.po.User;

@RestController
@RequestMapping("/users-test")
public class UserController {

ArrayList线程不安全,用synchronizedList使其线程安全。

private List<User> listUser=Collections.synchronizedList(new ArrayList<User>());

	
	/***
	 * 获取全部用户信息
	 * @return
	 */
	@GetMapping("/")
	public List<User> getUserList(){
		return listUser;
	}
	
	/***
	 * 新增用户
	 * @param user
	 * @return
	 */
	@PostMapping("/")
	public String createUser(User user) {
		listUser.add(user);
		return "success";
	}
	
	/***
	 * 获取指定id用户信息
	 * @param id
	 * @return
	 */
	@GetMapping("/{id}")
	public User getUser(@PathVariable("id")Long id) {
		for (User user : listUser) {
			if(user.getId()==id) {
				return user;
			}
		}
		return null;
	}
	/**
	 * 更新指定id用户信息
	 * @param id
	 * @param user
	 * @return
	 */
	@PutMapping("/{id}")
	public String updateUser(@PathVariable("id") Long id,User user) {
		for (User user2 : listUser) {
			if(user2.getId()==id) {
				user2.setName(user.getName());
				user2.setAge(user.getAge());
			}
		}
		return "success";
	}
	
	/***
	 * 删除指定id用户
	 * @param id
	 * @return
	 */
	@DeleteMapping("/{id}")
	public String deleteUser(@PathVariable("id") Long id) {
		
			listUser.remove(getUser(id));
			return "success";
		
	}
}

5、Postman测试RESTful接口

(1)、新增用户
post http://localhost:8080/users/
在这里插入图片描述

(2)、获取全部用户信息
get http://localhost:8080/users/
在这里插入图片描述

(3)、获取指定id用户信息
get http://localhost:8080/users/id
在这里插入图片描述

(4)、更新指定id用户信息
put http://localhost:8080/users/id
在这里插入图片描述

(5)、删除指定id用户信息
delete http://localhost:8080/users/id
在这里插入图片描述

六、SpringBoot Jdbc操作数据库

1、SpringBoot开启jdbc支持

刚才我们编写完成了针对用户数据的RESTful API,但是我们是用集合模拟的数据,在实际工作过程中需要把数据存储到数据库中,接下来我就带领大家来完成SpringBoot针对数据库的基本操作。

为了让SpringBoot支持jdbc数据操作,需要修改pom.xml
增加所需的jar

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

jdbc连接数据驱动(本次教学采用MySQL数据库),需要修改pom.xml
增加所需的jar

<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
</dependency>

最后修改src/main/resources/application.yml中配置数据源信息

#数据库jdbc连接url地址,serverTimezone设置数据库时区东八区
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8
    username: root
    password: 123
    driver-class-name: com.mysql.cj.jdbc.Driver

2、编写数据库操作业务接口

package com.jdbcdemo.service;
import java.util.List;
import com.jdbcdemo.po.User;
//用户数据操作业务接口
public interface UserService {

	//获取全部用户数据
	public List<User> getUserList();
	//新增用户数据
	public void createUser(User user);
	//获取指定id用户信息
	public User getUser(Long id);
	//更新指定id用户信息
	public void updateUser(Long id,User user);
	//删除指定id用户
	public void deleteUser(Long id);
}

3、编写数据库操作业务实现类

package com.jdbcdemo.service.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Service;

import com.jdbcdemo.po.User;
import com.jdbcdemo.service.UserService;
@Service
public class UserServiceImpl implements UserService {

	//SpringBoot提供的数据库操作类
	@Autowired
	JdbcTemplate jdbcTemplate;
	
	@Override
	public List<User> getUserList() {
    return jdbcTemplate.query("select * from users", new BeanPropertyRowMapper(User.class));
	}

	@Override
	public void createUser(User user) {
		jdbcTemplate.update("insert into users(name,age)values(?,?)",user.getName(),user.getAge());
	}

	@Override
	public User getUser(Long id) {
		return (User) jdbcTemplate.queryForObject("select * from user where id=?", new BeanPropertyRowMapper(User.class), id);
	}

	@Override
	public void updateUser(Long id, User user) {
		jdbcTemplate.update("update users set name=?,age=? where id=?",user.getName(),user.getAge(),id);

	}

	@Override
	public void deleteUser(Long id) {
		jdbcTemplate.update("delete from users where id=?",id);
	}

}

4、编写Controller

package com.jdbcdemo.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.jdbcdemo.po.User;
import com.jdbcdemo.service.UserService;

@RestController
@RequestMapping("/users")
public class UserControllerDb {

@Autowired
UserService userService;
	/***
	 * 获取全部用户信息
	 * @return
	 */
	@GetMapping("/")
	public List<User> getUserList(){
		return userService.getUserList();
	}
	
	/***
	 * 新增用户
	 * @param user
	 * @return
	 */
	@PostMapping("/")
	public String createUser(User user) {
		userService.createUser(user);
		return "success";
	}
	
	/***
	 * 获取指定id用户信息
	 * @param id
	 * @return
	 */
	@GetMapping("/{id}")
	public User getUser(@PathVariable("id")Long id) {
		
		return userService.getUser(id);
	}
	/**
	 * 更新指定id用户信息
	 * @param id
	 * @param user
	 * @return
	 */
	@PutMapping("/{id}")
	public String updateUser(@PathVariable("id") Long id,User user) {
		userService.updateUser(id, user);
		return "success";
	}
	
	/***
	 * 删除指定id用户
	 * @param id
	 * @return
	 */
	@DeleteMapping("/{id}")
	public String deleteUser(@PathVariable("id") Long id) {
		
		userService.deleteUser(id);
			return "success";
		
	}
}

5、Postman测试RESTful接口

重新执行测试。

七、SpringBoot整合Druid数据源

SpringBoot的数据源 默认是 HikariDataSource

Spring Boot 2.x 自定义数据源 DruidDataSource(操作 mysql 数据库)https://blog.csdn.net/wangmx1993328/article/details/81865153

七、SpringBoot 整合Mybatis操作数据库

1、SpringBoot开启Mybatis支持

添加Mybatis起步依赖以及mysqljdbc驱动、连接池druid驱动

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.0.0</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.10</version>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>

2、修改SpringBoot配置文件application.yml

#配置数据源
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8
    type: com.alibaba.druid.pool.DruidDataSource
    username: root
    password: 123
    driver-class-name: com.mysql.jdbc.Driver

#springboot整合mybatis    
mybatis:
  # 加载mapper.xml
  mapper-locations: classpath:mapper/*.xml
  # 别名
  type-aliases-package: com.demo.po

3、创建实体bean User

package com.demo.po;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private Long id;
    private String name;
    private Integer age;
}

4、创建Dao接口,使用mybatis注解

package com.demo.dao;

import com.demo.po.User;
import org.apache.ibatis.annotations.*;

import java.util.List;
@Mapper
public interface UserDao {

    @Insert("insert into user(name,age) values(#{name},#{age})")
    public void save(User user);

    @Update("update user set name=#{name},age=#{age} where id=#{id}")
    public void update(User user);

    @Delete("delete from user where id=#{id}")
    public void delete(Long id);

    @Select("select * from user")
    public List<User> getAll();

    @Select("select * from user where id=#{id}")
    public User findOne(Long id);

}

5、创建Service接口

package com.demo.service;
import java.util.List;
import com.demo.po.User;
//用户数据操作业务接口
public interface UserService {

    //获取全部用户数据
    public List<User> getUserList();
    //新增用户数据
    public void createUser(User user);
    //获取指定id用户信息
    public User getUser(Long id);
    //更新指定id用户信息
    public void updateUser(Long id,User user);
    //删除指定id用户
    public void deleteUser(Long id);
}

6、创建Service实现类

package com.demo.service.impl;

import com.demo.dao.UserDao;
import com.demo.po.User;
import com.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public List<User> getUserList() {
        return userDao.getAll();
    }

    @Override
    public void createUser(User user) {
        userDao.save(user);
    }

    @Override
    public User getUser(Long id) {
        return userDao.findOne(id);
    }

    @Override
    public void updateUser(Long id, User user) {
        user.setId(id);
       userDao.update(user);
    }

    @Override
    public void deleteUser(Long id) {
      userDao.delete(id);
    }
}

7、创建Controller

package com.demo.controller;

import com.demo.po.User;
import com.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    UserService userService;
    /***
     * 获取全部用户信息
     * @return
     */
    @GetMapping("/")
    public List<User> getUserList(){
        return userService.getUserList();
    }

    /***
     * 新增用户
     * @param user
     * @return
     */
    @PostMapping("/")
    public String createUser(User user) {
        userService.createUser(user);
        return "success";
    }

    /***
     * 获取指定id用户信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public User getUser(@PathVariable("id")Long id) {

        return userService.getUser(id);
    }
    /**
     * 更新指定id用户信息
     * @param id
     * @param user
     * @return
     */
    @PutMapping("/{id}")
    public String updateUser(@PathVariable("id") Long id,User user) {
        userService.updateUser(id, user);
        return "success";
    }

    /***
     * 删除指定id用户
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public String deleteUser(@PathVariable("id") Long id) {

        userService.deleteUser(id);
        return "success";

    }
}

8、修改SpringBoot程序主启动类,增加扫描dao接口

@SpringBootApplication
@MapperScan("com.demo.dao")
public class DemoApplication {

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

}

9、Postman测试RESTful接口

重新执行测试。

八、SpringBoot整合SpringJPA

Springboot整合SpringJPA
https://blog.csdn.net/qq_39086296/article/details/90485645
jpa条件查询案例(这个帖子的第6章):https://blog.csdn.net/t18776050775/article/details/104221842
spring data jpa 入门:https://www.cnblogs.com/chenglc/p/11226693.html

九、SpringBoot整合MyBatisPlus

https://blog.csdn.net/BigDevil_/article/details/108848822

十、SpringBoot整合encache

转载https://www.cnblogs.com/yiidian/p/12297759.html

十一、SpringBoot的拦截器

https://www.cnblogs.com/anenyang/p/10932203.html

十二、SpringBoot的SpringUtil

ApplicationContextAware 通过它Spring容器会自动把上下文环境对象调用ApplicationContextAware接口中的setApplicationContext方法。

我们在ApplicationContextAware的实现类中,就可以通过这个上下文环境对象得到Spring容器中的Bean。

https://www.cnblogs.com/loong-hon/p/10917755.html


import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringUtil implements ApplicationContextAware{
	
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if(SpringUtil.applicationContext == null) {
            SpringUtil.applicationContext = applicationContext;
        }
    }

    //获取applicationContext
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    //通过name获取 Bean.
    public static Object getBean(String name){
        return getApplicationContext().getBean(name);
    }

    //通过class获取Bean.
    public static <T> T getBean(Class<T> clazz){
        return getApplicationContext().getBean(clazz);
    }

    //通过name,以及Clazz返回指定的Bean
    public static <T> T getBean(String name,Class<T> clazz){
        return getApplicationContext().getBean(name, clazz);
    }

    public static String[] getBeans(){
        return getApplicationContext().getBeanDefinitionNames();
    }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值