文章目录
一、使用springboot添加依赖
- 方式一:继承spring-boot-starter-parent项目
- 方式二:导入spring-boot-dependencies项目依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.12.RELEASE</version>
</parent>
web项目需另外添加如下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
排除自带的tomcat容器:
<!--web 开发的起步依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!--排除TomCat 依赖-->
<exclusions>
<exclusion>
<artifactId>spring-boot-starter-tomcat</artifactId>
<groupId>org.springframework.boot</groupId>
</exclusion>
</exclusions>
</dependency>
spring-boot-starter-parent作用
spring-boot-starter-parent是一个springboot项目的父工程,它定义了很多当前项目的规范,比如:
a:定义了Java编译版本为 1.8.
b:使用UTF-8格式编码。
c:继承自spring-boot-dependencies,这个里面定义了依赖的版本,也是因为继承了这个依赖,我们在写依赖时才不需要写版本号。
d:执行打包操作的配置。
e:自动化的资源过滤。
f: 自动化的插件配置。
g:针对 application.properties 和application.yml 的资源过滤,包括通过profile定义不同的环境配置文件,application-dev.properties 和application-pro.properties.
spring-boot-starter-web作用
Spring Boot 为 Spring MVC 提供了自动配置,并在 Spring MVC 默认功能的基础上添加了以下特性:
a:引入了 ContentNegotiatingViewResolver 和 BeanNameViewResolver(视图解析器)
b:对包括 WebJars 在内的静态资源的支持
c:自动注册 Converter、GenericConverter 和 Formatter (转换器和格式化器)
d:对 HttpMessageConverters 的支持(Spring MVC 中用于转换 HTTP 请求和响应的消息转换器)
e:自动注册 MessageCodesResolver(用于定义错误代码生成规则)
f:支持对静态首页(index.html)的访问
g:自动使用 ConfigurableWebBindingInitializer
二、springboot 热加载与热部署使用
1、热加载与热部署
- 热加载是指可以在不重启服务的情况下让更改的代码生效,热加载可以显著的提升开发以及调试的效率。
- 热部署就是已经运行了项目,更改之后,不需要重新tomcat,但是会清空内存,重新打包,重新解压war包运行。【好处】一个tomcat多个项目,不必因为tomcat停止而停止其他的项目
2、原理
- 热加载基于 Java 的类加载器实现的,服务器会监听 class 文件改变,包括web-inf/class,wen-inf/lib,web-inf/web.xml等文件,若发生更改,则局部进行加载,不清空session ,不释放内存。
- 热部署
运行tomcat项目需要3步
1.打包并指定给tomcat
2.启动tomcat
3.自动解压war包并运行(第三步和第二步一起的)
3、注意点
- 要考虑内存溢出的情况,
- 由于热加载的不安全性,不会用于正式的生产环境。
4、使用配置
1)tomcat项目
- 热加载:在server.xml -> context 属性中 设置 reloadable=“true”
<Context docBase="xxx" path="/xxx" reloadable="true"/>
- 热部署:在server.xml -> context 属性中 设置 autoDeploy=“true”
<Context docBase="xxx" path="/xxx" autoDeploy="true"/>
2)没有tomcat项目
第一步:添加依赖
<!-- 热部署方法1spring boot devtools 依赖包. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
<scope>true</scope>
</dependency>
<!-- 这是spring boot devtool plugin 热部署1常用-->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<!--fork : 如果没有该项配置,这个devtools不会起作用,即应用不会restart -->
<fork>true</fork>
</configuration>
</plugin>
第二步:application.yml配置文件中添加配置
---
spring:
devtools:
restart:
#热部署生效
enabled: true
#设置重启的目录
#additional-paths: src/main/java
#classpath目录下的WEB-INF文件夹内容修改不重启
exclude: WEB-INF/*
第三步:eclipse或者其他IDE设置“自动编译”