SpringBoot(尚硅谷)
第一个springboot应用
根据官方文档改进
新建一个maven工程,在pom.xml中导入parent
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.5.6</version> </parent>导入spring boot依赖
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>在/src/main/java下新建spring boot主类:固定格式
@SpringBootApplication public class MyApplication { public static void main(String[] args){ SpringApplication.run(MyApplication.class,args); } }编写controller类,实现请求跳转
@RestController public class MyController { @RequestMapping("/hello")//1. 浏览器发送/hello请求 public String hello(){ return "Hello, Spring Boot!";//2. 将字符串返回给调用者 } }@RestController = @Controller + @ ResponseBody
运行MyApplication的main方法即可
spring boot项目可以作为独立的可运行的jars
添加spring-boot-maven-plugin到pom.xml
<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>执行mvn package命令
在 项目/target目录下,使用cmd执行 Java - jar xxx.jar
了解自动配置原理
依赖管理
parent(spring-boot-dependencies)中声明了所有开发中常用的依赖的版本号 ---> 自动版本仲裁机制
如果需要自定义修改依赖的版本:在pom.xml中添加
<properties> <mysql.version>5.1.4</mysql.version> </properties>starter-场景启动器starter是一组依赖描述符,官方定义的starter格式为spring-boot-starter-*; *表示场景
spring boot支持的场景在官方文档都有描述
所有场景启动器最底层的依赖:spring-boot-starter
自动配置
@Configuration注解声明被注解修饰的类为配置类,可以使用方法注册组件。将组件注册到Bean容器
@Configuration public class MyConfig { @Bean("pet")//以方法名作为组件的id;返回类型就是组件类型;返回值是组件在容器中的实例 public pet pet01(){ return new pet("Tom",2); } }检查Bean容器中的组件:在spring boot主类中打印所有bean容器存在的组件
@SpringBootApplication public class MyApplication { public static void main(String[] args){ ConfigurableApplicationContext run = SpringApplication.run(MyApplication.class, args); String[] names = run.getBeanDefinitionNames(); for (String name : names) { System.out.println(name); } } }proxyBeanMethods:代理bean的方法
proxyBeanMethods=true 单例模式,Full模式,每次加载都在Bean容器中找组件,保证取得的组件为ioc中的同一组件
proxyBeanMethods=false Lite 轻量级模式,启动不会去Bean容器中找组件,启动速度快,不需要组件依赖时使用
@Bean、@Componet、@Contorller、@Service、@Repository
@ComponentScan、@Import@Import注解也是向容器中导入组件,在config类上导入
@Import({pet.class})@Conditional按照条件进行组件注解;是一个根注解,有很多子注解
加在方法上,满足条件,该方法才能注册组件
加在类上,满足条件,该类中的所有方法才能注册组件
@ConditionalOnBean(name = "xxx")@ImportResource导入资源:将beans.xml配置文件中的<bean>标签的组件注册到容器中
在类上添加注解
@ImportResource("classpath:/beans.xml")配置绑定
@Component + @ConfigurationProperties
假设有一个pojo类car,有两个属性brand和price
@Controller @ConfigurationProperties(prefix = "mycar") public class Car {}写配置文件,在application.properties中
mycar.brand=BYD mycar.price=10000写controller
@Autowired public Car car; @RequestMapping("/car") public Car car01(){ return car; }验证
在浏览器输入localhost:8080/car@ConfigurationProperties + @EnableConfigurationProperties
在MyConfig类上添加注解
@EnableConfigurationProperties(Car.class)
开启Car的配置绑定功能
把这个Car自动注册到容器中
自动配置原理
@SpringBootApplication @SpringBootConfiguration @EnableAutoConfiguration @ComponentScan最佳实践
@SpringBootConfiguration
是一个个@Configuration,代表当前类是一个配置类
ComponentScan
指定扫描位置
EnableAutoConfiguration
@AutoConfigurationPackage @Import({AutoConfigurationImportSelector.class}) public @interface EnableAutoConfiguration {}@AutoConfigurationPackage自动配置包:
@Import({Registrar.class}) public @interface AutoConfigurationPackage {}通过Registrar将指定包(主类,被@SpringBootApplication)下的所有组件批量导入
@Import({AutoConfigurationImportSelector.class})getAutoConfigurationEntry(annotationMetadata);
引入场景依赖
查看自动配置了哪些
是否需要修改
参照文档修改配置项
自定义加入或者替换组件
……
开发小技巧
Lombok简化Java bean的开发
//lombok常用注解 @Data//生成所有属性的getter/setter方法 @ToString//编译时生成toString()方法 @AllArgsConstructor//所有参数的有参构造器 @NoArgsConstructor//无参构造器dev-tools(官方不推荐😂)热更新。引入依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency>在项目中 Ctrl+F9 重新编译项目
Spring Boot2 核心功能
配置文件
properties
yaml
web开发
静态资源只要静态资源放在类路径下:/static /public /resources /META-INF/resources目录下都能被找到
静态资源添加前缀路径:方便拦截器的配置
spring: mvc: static-path-pattern: /res/**以后访问需要localhost:8080/res/资源名
首页图标 favicon
将index.jsp放在静态资源路径下能自动识别
处理/index请求的controller
在静态资源路径下添加favicon.ico文件,即可自动加载
静态资源配置原理
请求处理REST风格,需要手动开启
spring: mvc: hiddenmethod: filter: enabled: trueController类
@RequestMapping(value = "/user" , method = RequestMethod.GET) public String getUser(){ return "GET-张三"; } @RequestMapping(value = "/user",method = RequestMethod.POST) public String saveUser(){ return "POST-张三"; } @RequestMapping(value = "/user" ,method = RequestMethod.PUT) public String putUser(){ return "PUT-张三"; } @RequestMapping(value = "/user" ,method = RequestMethod.DELETE) public String DeleteUser(){ return "DELETE-张三"; }index.html表单内容
<form action="/user" method="get"> <input value="REST-GET 提交" type="submit"/> </form> <form action="/user" method="post"> <input value="REST-POST 提交" type="submit"/> </form> <form action="/user" method="post"> <input name="_method" type="hidden" value="DELETE"/> <input value="REST-delete 提交" type="submit"/> </form> <form action="/user" method="post"> <input name="_method" type="hidden" value="PUT"/> <input value="REST-put 提交" type="submit"/> </form>原理:
表单提交会带上_method=PUT
请求过来被HiddenHttpMethodFilter拦截,判断是否为POST
也可以直接使用注解
@GetMapping("/user") @PostMapping("/user") @PutMapping("/user") @DeleteMapping("/user")请求映射原理浏览器发送请求,程序是如何找到具体方法执行的
SpringMVC功能分析都从
org.springframework.web.servlet.DispatcherServlet
->doDispatch()
mappedHandler = getHandler(processedRequest);//找到当前请求使用哪个Handdler(Controller的方法)处理getHandler()方法
@Nullable protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception { if (this.handlerMappings != null) { for (HandlerMapping mapping : this.handlerMappings) { HandlerExecutionChain handler = mapping.getHandler(request); if (handler != null) { return handler; } } } return null; }HandlerMappings中保存了所有handler
第一个RequesMappingHandlerMapping中保存了所有路径的映射
先根据路径找到所有对应的,再去遍历取最合适的
常用注解使用@RestController public class ParameterTestController { @GetMapping("/car/{id}/owner/{username}") public Map<String,Object> getCar(@PathVariable("id") Integer id,//路径变量 @PathVariable("username") String name, @PathVariable Map<String,String> pv, @RequestHeader("User-Agent") String userAgent,//获取请求头 @RequestParam("age") Integer age,//获取请求参数,路径问好后面的内容 @RequestParam("inters") List<String> inters, @RequestParam Map<String,String> params, @CookieValue("_ga") String _ga){//获取cookie Map<String,Object> map = new HashMap<>(); map.put("id",id); map.put("name",name); map.put("pv",pv); map.put("userAgent",userAgent); map.put("age",age); map.put("inters",inters); map.put("params",params); map.put("_ga",_ge); return map; } }对应的index.xml中添加
<a href="/car/3/owner/xxxx?age=18&inters=basketball&inters=game">测试常用注解</a>视图解析与模板引擎
thymeleaf
基本语法
表达式名字 语法 用途 变量取值 ${...} 获取请求域、session域、对象等 选择变量 *{...} 获取上下文对象值 消息 #{...} 获取国际化等值 链接 @{...} 生成链接 片段表达式 ~{...} jsp:include引用,引入公共页面 使用
引入依赖
导入thymeleaf名称空间
<html lang="en" xmlns:th="http://www.thymeleaf.org">数据访问
单元测试
指标监控
原理解析
第一个springboot应用
根据官方文档改进
-
新建一个maven工程,在pom.xml中导入parent
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.5.6</version> </parent>
-
导入spring boot依赖
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
-
在/src/main/java下新建spring boot主类:固定格式
@SpringBootApplication public class MyApplication { public static void main(String[] args){ SpringApplication.run(MyApplication.class,args); } }
-
编写controller类,实现请求跳转
@RestController public class MyController { @RequestMapping("/hello")//1. 浏览器发送/hello请求 public String hello(){ return "Hello, Spring Boot!";//2. 将字符串返回给调用者 } }
@RestController = @Controller + @ ResponseBody
-
运行MyApplication的main方法即可
-
spring boot项目可以作为独立的可运行的jars
-
添加spring-boot-maven-plugin到pom.xml
<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>
-
执行mvn package命令
-
在target文件夹中就可以找到.jar;使用java -jar xxx.jar运行即可
-