本文发布于1268 天前,最后更新于686天前,其中的信息可能已经有所发展或是发生改变。
SpringBoot
- 自动装配
- 约定大于配置
微服务
是一种架构。打破all-in-one
第一个SpringBoot
- jdk1.8
- maven
- SpringBoot
- IDEA
官方提供快速生成网站,IDEA集成了。
官网创建
IDEA创建
第一个SpringBoot WEB应用
HelloController.java
package top.huii.hellospringboot.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/hello")
public class HelloController {
@GetMapping("h1")
@ResponseBody
public String hello(){
return "hello";
}
}
彩蛋——自定义banner
原理初探
自动配置
pom.xml
- spring-boot-dependencies:核心依赖在父工程中
- 在写或引入一些依赖,不需要指定版本
启动器
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
- SpringBoot启动场景
- 会将所有的功能场景变成一个个的启动器
- 我们要使用什么功能,就只需要找到对应的启动器就可以了
主程序
package top.huii.hellospringboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class HelloSpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(HelloSpringBootApplication.class, args);
}
}
- @SpringBootApplication表明是一个SpringBoot应用
- SpringBoot所有自动配置都是在启动的时候扫描并加载,但不一定生效,要判断条件是否成立,要导入对应的start就有对应的启动器。
配置文件
yaml
不推荐使用properties配置文件,推荐使用yaml
yaml对空格要求极高
student:
name: HUII
age: 12
松散绑定:last-name等同于lastName
多环境切换
最外层配置优先级最高
使用yaml还能这样
WEB开发
导入静态资源
在springboot下,可以使用一下方式处理静态资源
- webjars http://127.0.0.1:8080/webjars
- public, static, /**, resources http://127.0.0.1:8080/
- 优先级:resources>static(默认)>public
thymeleaf模板引擎
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
@RequestMapping("test")
public String test(){
return "test";
}
语法。。。
常用注解
- @Controller 控制器
- @RequestMapping(value = “/hello”) 设置路由
- @ResponseBody 直接返回字符串
- @RestController 相当于@Controller + @ResponseBody,返回json对象
- @GetMapping(value = “/hello”) 相当于@RequestMapping(value = “/hello”, method=RequestMethod.GET) 只接受GET方法请求。方式不对会报405错误
- @PostMapping(value = “/hello”) 相当于@RequestMapping(value = “/hello”, method=RequestMethod.POST) 只接受POST方法请求。
- @DeleteMapping(value = “/hello”)
- @PutMapping(value = “/hello”)
Restful风格
@RequestMapping("usr/{id}/{name}/{pwd}")
@ResponseBody
public Object user1(@PathVariable("id") Integer id, @PathVariable("name") String name, @PathVariable("pwd") String pwd){
User user = new User(id, name, pwd);
return user;
}
Redis
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
拦截器
public class UserInterceptor implements HandlerInterceptor {}