目录
1.什么是SpringBoot
Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置(约定大于配置)。通过这种方式,Spring Boot致力于在蓬勃发展的快速应用开发领域(rapid application development)成为领导者。
- SpringBoot是用来简化javaWeb开发的
- 他是约定大于配置的!
什么是微服务?
微服务是一种架构风格 是一种将单个应用程序开发为一套小型服务的方法,每个服务都在自己的进程中运行,并与轻量级机制(通常是 HTTP 资源 API)进行通信。这些服务是围绕业务功能构建的,可通过全自动部署机制独立部署。这些服务只有最低限度的集中管理,这些服务可以用不同的编程语言编写,并使用不同的数据存储技术
- 微服务是一种架构风格
- 可以使服务使用不同的语言进行编写
- 可以使用不同的数据库存储技术
创始人论文链接(建议查看):微服务 (martinfowler.com)
2.第一个SpringBoot程序
Spring官方提供了一个生成SpringBoot的网站,而IDE中集成了这个网站:https://start.spring.io/


SpringBoot中内嵌了一个Tomcat!
3.自定义启动图标与配置端口号
当我们创建好项目后(下好jar包),在此创建就非常快了,创建完成目录如下:

如果我们需要进行SpringBoot的配置就可以在resources(资源目录下)的application.properties中配置如:
# 修改端口号
server.port=8081
如果我们想要启动的时候自定义图标可以在,resources(资源目录下)新建一个banner.txt文件中放入我们的图文,则启动项目时就会加载了!SpringBoot会自动扫描!
推荐图画获取网站:Spring Boot banner在线生成工具,制作下载banner.txt,修改替换banner.txt文字实现自定义,个性化启动banner-bootschool.net
如:
4.原理初探
pom.xml
- 他的核心依赖在父工程:spring-boot-starter-parent(也是SpringBoot的核心依赖)
- 我们在SpringBoot导入包时不许要写版本信息,就是应为有这些版本仓库!
启动器:
<!-- SpringBoot启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
- 启动器就是,SpringBoot的使用场景
- 比如我们的spring-boot-starter-web就会帮我们自动导入web的jar包(使用Tomcat)来启动!
- SpringBoot将所有功能的场景变成了一个一个的启动器
主程序:
package com.example.springboot01;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
//@SpringBootApplication 用来标注这个类是一个SpringBoot的应用!
@SpringBootApplication
public class SpringBoot01Application {
public static void main(String[] args) {
//将SpringBoot的应用启动
SpringApplication.run(SpringBoot01Application.class, args);
}
}
@SpringBootApplication中包含的重要注解:
@SpringBootConfiguration //Spring的配置注解
|@Configuration //Spring配置
|@Component //表示这也是一个Spring的组件
@EnableAutoConfiguration //自动配置(自动装配)
|@AutoConfigurationPackage //自动装配包
|@Import({Registrar.class}) //包注册自动配置
|@Import({AutoConfigurationImportSelector.class}) //自动配置导入选择器
获取所有的配置(获取候选的配置):
List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes);

//所有的配置加载到配置类中
Properties properties = PropertiesLoaderUtils.loadProperties(resource);

结论:SpringBoot所有的配置文件,都是在启动的时候扫描并加载,spring.factories他所有的配置文件都在这里面,但是并不一定会生效,需要判断条件是否成立,只有导入对应的start,就有对应的启动器了,有了启动器自动装配就会生效,才会成功!
5.Spring配置
在Spring的配置中官方推荐使用yaml的配置文件(基础语法)如:
# 设置服务器
server:
port: 8080
# 普通的键值对
name:xiaobu
#对象
student:
name:xiaobu
age:16
#行内写法
student:{name:xiaobu,age:15}
#数组
pets:
- cat
- dog
- pig
pets:[cat,dog,pig]
而yaml厉害之处在于可以给实体类赋值如:

//需要使用该注解来表示属性配置
@ConfigurationProperties(prefix = "ymal中的初始名")
//如果需要使用properties文件来加载资源可以使用这个注解
@PropertySource(value = "classpath:xiaobu.properties")
在@Value中:
- @Value("${name}") 表示从配置文件中取name的值出来赋值
- @Value("name") 表示赋值给字段的值为name!
使用ymal注入:
# 设置服务器
server:
port: 8080
# 给对象注入值
dog:
id: 3
name: 旺旺
age: 15
sex: 公
person:
# 随机生产一个uuid
name: 小步_${random.uuid}
age: 16
happy: false
birth: 2022/5/25
maps: { k1: v1,k2: v2 }
lists:
- 唱歌
- 跳舞
- 打篮球
dog:
#${person.hello:hello}表示寻找person下的hello属性如果存在则显示他的属性如果不存在则显示hello
name: ${person.hello:hello}旺财
age: 3
JSR303校验:
JSR3030:就是用来判断赋值的属性是否合法!
<!-- JSR303校验: -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
基本规则:
空检查
@Null 验证对象是否为null
@NotNull 验证对象是否不为null, 无法查检长度为0的字符串
@NotBlank 检查约束字符串是不是Null还有被Trim的长度是否大于0,只对字符串,且会去掉前后空格.
@NotEmpty 检查约束元素是否为NULL或者是EMPTY.
Booelan检查
@AssertTrue 验证 Boolean 对象是否为 true
@AssertFalse 验证 Boolean 对象是否为 false
长度检查
@Size(min=, max=) 验证对象(Array,Collection,Map,String)长度是否在给定的范围之内
@Length(min=, max=) Validates that the annotated string is between min and max included.
日期检查
@Past 验证 Date 和 Calendar 对象是否在当前时间之前,验证成立的话被注释的元素一定是一个过去的日期
@Future 验证 Date 和 Calendar 对象是否在当前时间之后 ,验证成立的话被注释的元素一定是一个将来的日期
@Pattern 验证 String 对象是否符合正则表达式的规则,被注释的元素符合制定的正则表达式,regexp:正则表达式 flags: 指定 Pattern.Flag 的数组,表示正则表达式的相关选项。
数值检查
建议使用在Stirng,Integer类型,不建议使用在int类型上,因为表单值为“”时无法转换为int,但可以转换为Stirng为”“,Integer为null
@Min 验证 Number 和 String 对象是否大等于指定的值
@Max 验证 Number 和 String 对象是否小等于指定的值
@DecimalMax 被标注的值必须不大于约束中指定的最大值. 这个约束的参数是一个通过BigDecimal定义的最大值的字符串表示.小数存在精度
@DecimalMin 被标注的值必须不小于约束中指定的最小值. 这个约束的参数是一个通过BigDecimal定义的最小值的字符串表示.小数存在精度
@Digits 验证 Number 和 String 的构成是否合法
@Digits(integer=,fraction=) 验证字符串是否是符合指定格式的数字,interger指定整数精度,fraction指定小数精度。
@Range(min=, max=) 被指定的元素必须在合适的范围内
@Range(min=10000,max=50000,message=”range.bean.wage”)
@Valid 递归的对关联对象进行校验, 如果关联对象是个集合或者数组,那么对其中的元素进行递归校验,如果是一个map,则对其中的值部分进行校验.(是否进行递归验证)
@CreditCardNumber信用卡验证
@Email 验证是否是邮件地址,如果为null,不进行验证,算通过验证。
@ScriptAssert(lang= ,script=, alias=)
@URL(protocol=,host=, port=,regexp=, flags=)
-- 同时他也支持正则表达式,可以自定义规则!
如:
@Email(message = "邮箱格式错误")
private String mail;

yml配置文件:
yml配置文件可以通过---来表示多套配置如:
server:
port: 8081
---
server:
port: 8082
---
server:
port: 8083
而他们的配置都是SpringBoot中的配置类去接收的,ServerProperties类中包含了很多基础配置:
private Integer port;
private InetAddress address;
@NestedConfigurationProperty
private final ErrorProperties error = new ErrorProperties();
private ServerProperties.ForwardHeadersStrategy forwardHeadersStrategy;
private String serverHeader;
private DataSize maxHttpHeaderSize = DataSize.ofKilobytes(8L);
private Shutdown shutdown;
@NestedConfigurationProperty
private Ssl ssl;
@NestedConfigurationProperty
private final Compression compression;
@NestedConfigurationProperty
private final Http2 http2;
private final ServerProperties.Servlet servlet;
private final ServerProperties.Reactive reactive;
private final ServerProperties.Tomcat tomcat;
private final ServerProperties.Jetty jetty;
private final ServerProperties.Netty netty;
private final ServerProperties.Undertow undertow;
@ConditionalOnBean(仅仅在当前上下文中存在某个对象时,才会实例化一个Bean)
@ConditionalOnClass(某个class位于类路径上,才会实例化一个Bean)
@ConditionalOnExpression(当表达式为true的时候,才会实例化一个Bean)
@ConditionalOnMissingBean(仅仅在当前上下文中不存在某个对象时,才会实例化一个Bean)
@ConditionalOnMissingClass(某个class类路径上不存在的时候,才会实例化一个Bean)
@ConditionalOnNotWebApplication(不是web应用)
这些注解是用来判断是否启用这个类,@ConditionalOn*是SpringBoot的核心注解

6.Web开发
在SpringBoot中我们可以使用以下方式处理静态资源:
- webjars
- public,static,/**,resources
- 优先级:resources>static(默认)>public
如果想要设置首页可以直接在静态资源下创建index.hmtl页面SpringBoot会自动扫描!
templatesl目录下的文件用户不能直接访问需要通过程序的跳转才能访问!
我们如果需要通过控制器转跳页面则需要导入thymeleaf模板依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
thymeleaf模板:
文档:Thymeleaf教程(10分钟入门) (biancheng.net)
如果需要在html中使用thymeleaf则必须导入:
<html lang="en" xmlns:th="http://www.thymeleaf.org">
如:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--转义th:text-->
<h1 th:text="${msg}"></h1>
<!--非转义th:th:utext -->
<h1 th:utext="${msg}"></h1>
<!-- 遍历值:th:each="hello:${msg}" 遍历传来的值,并命名hello 可以通过[[${}}]]来进行取值 -->
<h1 th:each="hello:${msg}">[[${hello}}]]</h1>
</body>
</html>
扩展视图解析器:
package com.example.springboot03.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.Locale;
//如果想要扩展视图解析器就可以这样,DispatcherServlet的doDispatch()方法会自动帮我们进行视图解析,只需要把他交给SpringBoot就好了!
//实现@Configuration代表扩展MVC配置
@Configuration
public class MyMvcConfig implements WebMvcConfigurer { //WebMvcConfigurer webMvc配置器
//扩展视图
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/xiaobu").setViewName("test");
}
@Bean
public ViewResolver getMyViewResolver(){
return new MyViewResolver();
}
private static class MyViewResolver implements ViewResolver {
@Override
public View resolveViewName(String viewName, Locale locale) throws Exception {
return null;
}
}
}
注意:如果项目中有@Configuration类可则该类不可以使用@EnableWebMvc(改注解导入了一个类),而在WebMvcAutoConfiguration类中会判断@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })如果存在这些类则自动配置不生效,则会跳转出错等~

6万+

被折叠的 条评论
为什么被折叠?



