SpringBoot 初学
- 一、微服务
- 二、Spring Boot
- 1. Spring Boot 开发每一个微服务模块
- 2. 目录结构
- 3. 内置tomcat,并不需要打成war包再执行
- 4. @SpringBootApplication :Spring Boot的主配置类
- 5. 自动装配原理(@EnableAutoConfiguration)
- 6. 配置文件
- 7.@ImportResource
- 8. Spring Boot全局配置文件中的 占位符表达式
- 9. 多环境设置及切换 (profile)
- 10. 配置文件的位置
- 11. 日志
- 12. Spring Boot开发web项目(静态项目、html、js、css !!!直接放入到 静态资源路径 中即可)。
- 13. Spring Boot 整合jsp开发
一、微服务
一个项目 可以由多个 小型服务(微服务)构成
如:项目A:支付功能、订单功能、等多个小型服务(模块)
彼此之间通过协议连接
二、Spring Boot
1. Spring Boot 开发每一个微服务模块
a. 简化j2ee开发
b. 整个spring技术栈的整合(整合springmvc spring)
c. 整个j2ee技术的整合(整合redis、Mybatis)
2. 目录结构
resources:
static:静态资源(js、css、图片、音频、视频)
templates:模板文件(模板引擎freemarker,thymeleaf;默认不支持jsp)
application.properties:spring配置文件
3. 内置tomcat,并不需要打成war包再执行
Spring Boot 内置了tomcat,并不需要打成war包再执行
可以在application.properties对端口号等服务端信息进行配置
<!--继承常用版本号(parent)-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
Spring Boot将各个应用/三方框架 设置成了一个个“场景”starter,直接引用即可。
选完之后就会将 该场景所需要的所有依赖 自动注入。例如选择web:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
就会将web所需相关的依赖(tomcat、json等)全部引入本项目中。
4. @SpringBootApplication :Spring Boot的主配置类
该注解包含:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
@Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
4.1 @SpringBootConfiguration : 自己写的代码,Spring Boot通过该注解自动帮我们配置。
其中主要包含@Configuration,表示“配置类”(配置文件:spring.xml 可用配置类代替配置文件)
a. 该类是一个配置类
b. 在Spring Boot加了@Configuration注解的类,会自动纳入spring容器(在spring中加了@Component,会自动纳入spring容器)
@Configuration
public class A{}//表示A是一个 用于 配置 的类
4.2 @EnableAutoConfiguration : 使 Spring Boot可以 自动配置
4.2.1 原则:约定由于配置(之前已经约定好了,不用配置了)。
4.2.2 包含了以下等注解
a. @AutoConfigurationPackage // 引入自己写的包。
可以找到我们用了@SpringBootApplication 的所在类的包名,作用:会将我们自己写的类所在的包及其所有的子包 全部纳入spring容器(不需要配置包扫描器等)(com.sb.xxx.xxxx)。
b. @Import({AutoConfigurationImportSelector.class}) : 引入第三方依赖。
AutoConfigurationImportSelector通过selectImports()函数引入第三方依赖(jar包、配置等)
Spring Boot在启动时,会根据 spring-boot-autoconfigure-2.4.3.jar 中的 (FACTORIES_RESOURCE_LOCATION=)META-INF/spring.factories进行声明,并将这些依赖引入本项目,通过@EnableAutoConfiguration开启使用。
spring-boot-autoconfigure-2.4.3.jar/META-INF/spring.factories( “# Auto Configure” 中 找到相应的三方依赖(暂时131个),其第三方包都在 spring-boot-autoconfigure-2.4.3.jar/org.springframework.boot.autoconfigure 目录下)。
spring-boot-autoconfigure-2.4.3.jar 中包含了 J2EE整合体系中 需要的依赖。
5. 自动装配原理(@EnableAutoConfiguration)
自动装配原理(@EnableAutoConfiguration)(在“# Auto Configure” 中的那些第三方依赖/配置/包)
自动装配的类(例如HttpEncodingAutoConfiguration)中:包含了
a. @Configuration: 表示此类事一个配置类;将此类纳入springioc容器
b. @EnableConfigurationProperties(ServerProperties.class) : 通过ServerProperties将编码默认为 UTF-8
c. @ConditionalOnWebApplication、@ConditionalOnClass、@ConditionalOnProperty 等:
每一个 XxxAutoConfiguration 都有很多条件 @ConditionalOnXxx,当这些条件都满足时,测该配置 自动装配生效。
但是我们可以在 application.properties中修改:
-- @ConditionalOnProperty 的prefix的 内容.属性名=值
例:@ConditionalOnProperty(prefix = "server.servlet.encoding", value = "enabled", matchIfMissing = true)
(eg:server.servlet.encoding.charset=GBK)。
-- @EnableConfigurationProperties 对应的XxxProperties(eg:@ConfigurationProperties(prefix = "spring.data.mongodb"))类中的prefix的内容.属性名
当属性满足所有要求(ConditionalOnXXX)时,此条件成立:要求:如果没有配置 server.servlet.encoding.enabled=xxx(GBK等),则成立。
d. 如何知道springboot开启了哪些自动装配、禁止了哪些自动装配:application.properties中加 debug=true 即可。
日志中 Positive matches 表示 spring boot 自动开启了的转配内容;
Negative matches 表示 spring boot 没有自动开启的装配内容
e. springboot就是用过 XxxAutoConfiguration 实现自动装配,如果想要修改默认值,通过 XxxProperties 中的 prefix 进行修改。(web.xml spring mvc.xml)
6. 配置文件
- 6.1 作用: spring boot 自动装配(约定:8080,UTF-8 。。。)。可以使用配置文件 对默认的配置 进行修改
- 6.2 默认全局配置文件:
- 6.2.1 application.properties : key=value
- 6.2.2 application.yml : key:空格value (“yaml ain’t myarkup language , 不是一个标记文档”)
- a. 尝试在 yml 文件中填写数据,注入到 bean对象 中
- b. 默认不加引号,但加双引号可以使用 转义符 (\n)。 eg: {province: “广\n东”,city: 深圳,zone: 福田}。
- c. 集合、数组中括号[];map和对象属性用大括号{}。中括号可以省略,大括号不可以省略。
- d. 集合、数组写法:
skills: 编程,金融 # 行内写法 #或 skills: [编程, 金融] # 行内写法 #或 skills: [编程, 金融] # 行内写法 #或 skills: - 编程 - 金融
- e. Map 和 对象
location: {province: 广东,city: 深圳,zone: 福田} # 行内写法 #或 location: province: 广东 city: 惠州 zone: 惠城 #或 pet: {nickName: qq,strain: 猫} #或 pet: nickName: qq strain: 猫
- 6.3 application.properties 和 application.yum 在给对象bean注入值时,可以互补;与 @Value 、 SpEL 也可以互补。
- 注值 需要给对象添加注解:
@ConfigurationProperties(prefix = "student")//通过 该注解 引入配置文件的值。//配置yml的数据 prefix的值对应yml文件中的值 @Value("张三") //说明:@ConfigurationProperties 是把配置文件的值 批量注入到 bean;@Value 是对 单个属性 注值。
- 注值优先级:
application.properties > application.yum > @Value
@ConfigurationProperties > @Value
- 注值 需要给对象添加注解:
- 6.4 其它文件:xml : 是一个标记文档
<server> <port>8080</port> <path>/a/b/c</path> </server>
- 6.5 如果要使用 非默认全局配置文件(config.properties)时,需要给 对象 加注解: @PropertySource({“classpath:config.properties”})
但是,@PropertySource 注解只能加载 properties 文件,不能加载yml - 7.6 通过 配置文件、注解 给 对象 注入值
# 通过yml给对象注入值 ---对象bean:--- @Component @ConfigurationProperties(prefix = "student") public class Student {} ---yml文件:有多种写法--- student: # name: cwh # 在application.properties中写也行,可以 互补 age: 23 # 当properties和yml都存在时,先用application.properties里的 sex: true birthday: 2021/01/01 location: # {province: 广东,city: 深圳,zone: 福田} # 行内写法 province: 广东 city: 惠州 zone: 惠城 hobbies: 篮球1,游戏1 # 行内写法 # - 篮球 # - 游戏 skills: [编程1, 金融1] # 行内写法 # - 编程 # - 金融 pet: # {nickName: qq,strain: 猫} # 行内写法 # pet: # {nick-name: qq,strain: 猫} # 松散写法:nick-name nickName: qq strain: 猫
# 通过properties给对象注入值 student.age=24 student.name=vihem
//使用 注解@Value 通过对 对象的属性 进行注入 @Component //将此JavaBean放入到spring容器中 public class Student { private String name; private int age; @Value("false") private boolean sex; private Date birthday; private Map<String, Object> location; private String[] hobbies;//爱好 private List<String> skills; private Pet pet; //getter /setter }
#其他,比较@ConfigurationProperties @Value @ConfigurationProperties @Value 注值 批量注入 单个 松散语法(nick-name) 支持 不支持 (驼峰式 nickName) SpEL(SpringEL) 不支持 支持 JSR303数据校验 支持 不支持 注入 复杂类型 支持 不支持 简单类型: (8个基本类型/String/Date) 复杂类型: 除了简单类型 -------------------------------------------- 松散语法: ---对象bean:---- @ConfigurationProperties(prefix = "pet") public class Pet { private String nickName;//nick-name //set/get } ---yml文件:---- pet: nick-name: qq # nickName --------------- SpEL: ---对象bean:---- public class User { @Value("${user.uname}") private String userName; //get/set } ---yml文件:---- user: userName: xxx --------------- JSR303数据校验: ---对象bean:---- @ConfigurationProperties(prefix = "user") @Validated //开启JSR303数据校验的注解 public class User { @Email private String email; //set/get } ---yml文件:---- user: email: xxx.@qq.com ---------------
7.@ImportResource
Spring Boot 是 自动装配/自动配置
spring等配置文件 默认会被 Spring Boot 自动配置好。
如果要自己编写 spring等配置文件,Spring Boot默认不能识别。
如果需要识别 配置文件,需要用 @ImportResource 指定该配置文件:在 (Spring Boot主配置类)@SpringBootApplication 的配置类中添加:
@ImportResource(locations = {"classpath:spring.xml"})
不推荐手写 spring 配置文件。 配置:xml配置文件,通过注解配置。
Spring Boot 推荐使用 注解方式 进行配置: 写一个配置类 AppConfig , 使用注解: @Configuration @Bean。 如:
@Configuration
public class AppConfig {
@Bean //方法名就是 spring.xml的bean中id
public StudentService studentService(){
StudentService studentService = new StudentService();
// StudentDao studentDao = new StudentDao();
// studentService.setStudentDao(studentDao);
return studentService;
}
}
8. Spring Boot全局配置文件中的 占位符表达式
常用: 随机数:
${random.uuid}: uuid
${random.value} 随机字符串
${random.int} 随机整型数
${random.long} 随机长整型数
${random.int(10)} 10以内的整型数
${random.int[1024,65536]}: 指定随机数范围
引用变量值:
------application.properties------
stu.user.stuId=12131321321121321
------application.yml-------------
student:
stuId: ${stu.user.stuId:stuid000000} # 引用 application.properties 的值,并设置默认为 'stuid000000'(如果properties没有值,显示默认值)
9. 多环境设置及切换 (profile)
-
properties
springboot默认读取 application.properties 环境
当有多个配置文件: application-环境名.properties 如:开发环境 application-dev.properties 测试环境 application-test.properties
切换环境:
在 application.properties 中加:spring.profiles.active=环境名 如:spring.profiles.active=dev
-
yml
切换环境: 对于 application.yum :略有不同(下面是同一个文件中的/也可以是不同文件的)# 第一个环境(主环境): server: port: 8885 spring: profiles: active: dev #使用dev环境 --- # 第二个环境: server: port: 8886 spring: config: activate: on-profile: dev --- # 第三个环境: server: port: 8887 spring: config: activate: on-profile: test ---
-
动态切换
- i. 命令行方式:
- (1)通过编译器(Eclipse):Run Configuration -> Java Application-> Argument -> Program arguments :
–spring.profiles.active=环境名 - (2)通过maven打包: package 进入包目录 -> cmd -> java -jar jar包名 --spring.profiles.active=环境名
- (1)通过编译器(Eclipse):Run Configuration -> Java Application-> Argument -> Program arguments :
- ii. 运行的时候通过VM参数指定环境:
- 通过编译器(Eclipse):Run Configuration -> Argument -> VM arguments -> -Dspring.profiles.active=环境名
- i. 命令行方式:
10. 配置文件的位置
- 10.1 项目 内部 的配置文件:
properties 和 yml 相互补充,若冲突,properties 优先; 默认读取 application.properties 和 application.yml, 这两个文件 可以存在以下4个路径: file(普通路径):项目根目录/config file(普通路径):项目根目录 classpath(src/main/resources):项目根目录/config classpath(src/main/resources):项目根目录 !!注意: 若有冲突,优先级 从上往下。
- 10.2 项目 外部 的配置文件(批量配置的补救):
(1)通过编译器(Eclipse):Run Configuration -> Java Application-> Argument -> Program arguments : --spring.config.location=配置文件 绝对路径名 (2)内/外部文件都存在时,外部优先。 (3)命令参数:当一个jar包已经运行时,想更改某个配置时,只需添加外部配置文件,通过命令行进行调用 jar包: jar包路径 -> cmd -> java -jar jar包名 --spring.config.location=配置文件绝对路径名
- 10.3 项目运行参数(少数配置的补救):
(1)通过编译器(Eclipse):Run Configuration -> Java Application-> Argument -> Program arguments -> --server.port=8888 --server.context-path=/abc 等。 (2)命令参数:当一个jar包已经运行:jar包路径 -> cmd -> java -jar jar包名 --server.port=8888
- 10.4 优先级 : 命令参数(外部文件/命令行参数) > 内部文件
"https://docs.spring.io/spring-boot/docs/2.4.4/reference/html/spring-boot-features.html#boot-features-external-config" -> 2. Externalized Configuration
11. 日志
日志框架有:UCL JUL jboss-logging logback log4j log4j2 slf4j …
Spring Boot 默认 slf4j和logback(还有一个log4j)
日志级别优先级: trace<debug<info<warn<error<fatal<off
默认最小级别 :info
自定义级别 :配置文件中 logging.level.主配置类所在包=级别
日志打印格式:例如:%d{yyyy-MM-dd} [%thread] %-5level %logger{50} - %msg%n
# 修改日志默认级别为 error
logging.level.com.spring.hello=error
# 指定 生成日志文件,其路径和文件名
logging.file.name=classpath:springboot.log
# 指定在console打印日志 格式
# %d{yyyy-MM-dd} 日期
# %thread 线程名
# %-5level 显示日志级别,-5表示从左显示5个字符宽度
# %logger{50} 设置日志长度
# %msg 日志消息
# %n 回车
logging.pattern.console=%d{yyyy-MM-dd} [%thread] %-5level %logger{50} - %msg%n
# 指定在file打印日志 格式
logging.pattern.file=%d{yyyy-MM-dd} [%thread] %-5level %logger{50} - %msg%n
12. Spring Boot开发web项目(静态项目、html、js、css !!!直接放入到 静态资源路径 中即可)。
12.1 springboot是一个jar包,因此静态资源 不再存放到 webapp下,存放在:
存放路径通过: 类 WebMvcAutoConfiguration 的 addResourceHandlers()指定: /webjars/
.js、 .css变成了jar包
jar资源 通过 写入pom文件 以maven导入 :在下面网址查询:https://www.webjars.org/
eg:
<!-- 以前引入 js等静态资源,是将这些资源下载 并手工放入到webapp目录下;
而springboot 直接 以jar文件(maven)的形式引入项目中-->
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.6.0</version>
</dependency>
访问路径是(resource后面的路径): http://localhost:8080/webjars/jquery/3.6.0/jquery.js
12.2 如何自己写静态资源?如何放到springboot中?将自己写的静态资源 -> jar,同上(不推荐)。推荐: springboot自动扫描
springboot约定:将一些目录结构 设置成静态资源存放路径,我们的静态资源直接放入这些目录即可。
WebMvcAutoConfiguration.java -> addResourceHandlers() -> this.resourceProperties.getStaticLocations() -> this.staticLocations = CLASSPATH_RESOURCE_LOCATIONS; -> (WebProperties.java)CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};
静态资源路径:上面的CLASSPATH_RESOURCE_LOCATIONS中的四个(优先级从前到后)。
访问时不需要加前缀,只需要访问静态资源文件名:http://localhost:8080/sbw.html
12.3 默认欢迎页:index.html
WebMvcAutoConfiguration->welcomePageHandlerMapping()->this.getWelcomePage()->this.getIndexHtml()->location.createRelative("index.html");
http://localhost:8080/
12.4 网站的网页标签的 Logo 是固定名字的: favicon.ico。
自定义:直接把 favicon.ico 文件放入 静态资源路径即可。
12.5 设置自定义静态资源路径
addResourceHandlers->resourceProperties->Resources->ResourceProperties(extends Resources)->prefix = "spring.resources"
properties中加: spring.web.resources.static-locations=classpath:/res/,classpath:/img/
自定义之后,不能使用原来的默认值。
12.6 模板引擎-thymeleaf
12.6.1 动态资源:jsp(spring boot默认不支持)
推荐:模板引擎-thymeleaf: 将一个网页拆分为: 模板 + 数据。
添加依赖
12.6.2 使用 thymeleaf:ThymeleafAutoConfiguration\ThymeleafProperties
ThymeleafAutoConfiguration.class->ThymeleafProperties.class->public static final String DEFAULT_PREFIX = "classpath:/templates/";public static final String DEFAULT_SUFFIX = ".html";
所以只需要把 thymeleaf的html文件 放入到路径 classpath:/templates/ 下即可。
eg:
thymeleaf.html:
<p th:text="${welcome}">Welcome to thymeleaf!</p>
<!--先从${welcome}中取值,如果有值则直接显示之;否则显示 Welcome to thymeleaf!
th:text 就是 替换原有html的text值。
更多的:
<p id="pid" class="pclass" th:id="${welcome}" th:class="${welcome}" th:text="${welcome}">Welcome to thymeleaf!</p>
替换了 id、class、text。
th:html属性名=值 (类似于 c:属性名=值)
-->
Controller:
@RequestMapping("/welcome")
public String welcome(Map<String, Object> map){
map.put("welcome", "welcome thymeleaf.");//给request域中放welcome
//给thymeleaf 准备数据
return "thymeleaf";
}
12.6.3 th:xx 参见:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#attribute-precedence
其中: th:text 获取文本值 eg:<h1>hello</h1> 显示: 用 h1 渲染之后的 hello
th:utext 获取文本值(不转义) eg:<h1>hello</h1> 显示: 鸳鸯输出 <h1>hello</h1>
12.6.4 符号:${…}、*{…}、#{…}、@{…}、~{…} 参见:
https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#standard-expression-syntax
12.6.5 遍历:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#iteration
13. Spring Boot 整合jsp开发
springboot默认自带一个内置tomcat,不需要打war包,直接通过jar包即可运行。在pom文件中的Dependency Hierarchy 查看tomcat。
但要整合jsp开发,就需要 单独配置一个 外置的tomcat,且需要打 war包。
13.1 新建一个boot项目,war打包:
注意: provided 使项目打包时不需要将内置的tomcat一起打包。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
13.2 建立基本的web项目所需要的目录结构
webapp/WEB-INF
webapp/WEB-INF/web.xml (springboot自动配置,不需要要建立)
webapp/index.jsp
13.3 创建tomcat实例,并且部署
访问:端口/项目名/文件名:http://localhost:8080/sbj/
13.4 在打成war包的springboot项目中,启动tomcat服务器时,先启动tomcat,接着调用 主配置类同目录的 ServletInitializer 类 下的 configure 方法,configure 方法调用 主配置类,以此启动 springboot