文章目录
SpringBoot热部署
应⽤正在运⾏的时候升级功能,不需要重新启动应⽤。对于Java应⽤程序来说,热部署就是在运⾏时更新Java类⽂件。
SpringBoot2.x配置文件
常见的配置文件形式xml、yml、properties
xx.yml(YAML)
写 YAML 要⽐写 XML 快得多(⽆需关注标签或引号) 使⽤空格 Space 缩进表示分层,不同层次之间的缩进可以使⽤不同的空格数⽬。
key后⾯的冒号,后⾯⼀定要跟⼀个空格,树状结构
xx.properties(推荐)
Key=Value格式
常用:
#修改启动端口
server.port=8080
#session失效时间,30m表示30分钟
server.servlet.session.timeout=30m
# Maximum number of connections that the server accepts and processes at
any given time.
server.tomcat.max-connections=10000
# Maximum size of the HTTP post content.
server.tomcat.max-http-form-post-size=2MB
# Maximum amount of worker threads
server.tomcat.threads.max=200
SpringBoot注解配置文件映射属性和实体类
配置文件加载
1、Controller上⾯配置:@PropertySource({"classpath:resource.properties"})
2、增加属性:@Value("${test.name}") private String name;
运行结果:
实体类配置文件
1、添加 @Configuration注解;
2、使⽤ @PropertySource 注解指定配置⽂件位置;
3、使⽤ @ConfigurationProperties 注解,设置相关属性;
4、必须 通过注⼊IOC对象Resource 进来 , 才能在类中使⽤获取的配置⽂件值。
@Autowired private ServerSettings serverSettings;
运行结果:
SpringBoot2.x的单元测试
1、引⼊相关依赖
2、配置相关注解
3、常用单元测试注解
@before
@Test
@After
运行结果:
4、断言
判断程序结果是否符合预期:TestCase.assertEquals(expected,actual);
测试controller-Service层接口
运行结果:
MockMvc调用api层接口
测试Controller对外提供的接⼝
1、增加类注解 @AutoConfigureMockMvc
2、注⼊⼀个MockMvc类
3、perform执⾏⼀个RequestBuilder请求
andExpect
:添加ResultMatcher->MockMvcResultMatchers验证规则
andReturn
:最后返回相应的MvcResult->Response
Springboot2.X全局异常处理
不配全局服务端报错场景 1/0、空指针等,统⼀的错误⻚⾯或者错误码,对⽤户更友好。
在项目中配置全局异常
1、类添加注解
@ControllerAdvice
,如果需要返回json数据,则⽅法需要加@ResponseBody(不返回json数据)
@RestControllerAdvice
, 默认返回json数据,⽅法不需要加@ResponseBody(返回json数据)
2、方法添加处理器
捕获全局异常,处理所有不可知的异常@ExceptionHandler(value=Exception.class)
运行结果:
自定义全局异常返回页面
案例demo_project9项目
返回⾃定义异常界⾯,引⼊thymeleaf依赖
1、引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2、resource⽬录下新建templates,并新建error.html
3、前端html获取错误信息msg
运行结果:
可能遇到的问题
添加注解@ConfigurationProperties(prefix=“test”)时
遇到Spring Boot Configuration Annotation Processor not configured
在pom.xml添加依赖即可解决 (不添加依赖也可编译):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
配置文件注入失败
Could not resolve placeholder
根据springboot启动流程,会有⾃动扫描包没有扫描到相关注解,默认Spring框架实现会从声明@ComponentScan所在的类的package进⾏扫描,来⾃动注⼊,因此启动类最好放在根路径下⾯,或者指定扫描包范围spring-boot扫描启动类对应的目录和子⽬录