SpringBoot 使用技巧与心得
1. 配置类有3次机会可以去覆盖配置,这对于框架封装是很有好处的
1 // 2. 在 bean 生成后,populateBean() 时,在 application.yml 配置文件里面进行覆盖 2 @ConfigurationProperties(prefix = "cas") 3 public class CasConfiguration implements InitializingBean { 4 private String casServerUrl; 5 6 @Override 7 public void afterPropertiesSet() throws Exception { 8 // 3. 在生成了 bean 之后,populateBean() 之后,还有一次机会进行配置覆盖 9 ... 10 } 11 } 12 13 14 使用 BeanMethod 的方式定义 bean 的时候,可以对配置进行第一次覆盖 15 @Bean 16 public CasConfiguration casConfiguration(){ 17 CasConfiguration cas = new CasConfiguration(); 18 // 1. 在 bean 生成之前进行配置初始化 19 ... 20 return cas; 21 }
2. 实现了 SmartLifecycle 的 bean,且 isAutoStartup() 是 true 的话,spring 容器在 refresh() 时就会自动调用 start()
3. SpringBoot 中 开启 SpringMVC debug日志,可以打印请求的详细信息
springboot version: 2.2.2.RELEASE
spring:
http:
log-request-details: true
logging:
level:
org.springframework.web: DEBUG
pattern:
console: '%d{yyyy-MM-dd HH:mm:ss.SSS}|%p|%t|%c{60}:%line|%X{traceId}|%m%ex%n'
输出示例:
2021-07-07 17:47:01.461|DEBUG|http-nio-8080-exec-1|org.springframework.web.servlet.DispatcherServlet:91||POST "/demo/saveUser", parameters={} 2021-07-07 17:47:01.465|DEBUG|http-nio-8080-exec-1|o.s.w.s.mvc.method.annotation.RequestMappingHandlerMapping:412||Mapped to com.kvn.mvc.DemoController#saveUser(User) 2021-07-07 17:47:03.429|DEBUG|http-nio-8080-exec-1|o.s.w.s.m.m.annotation.RequestResponseBodyMethodProcessor:91||Read "application/json;charset=UTF-8" to [User{id=null, name='www'}] 2021-07-07 17:47:03.451|DEBUG|http-nio-8080-exec-1|o.s.w.s.m.m.annotation.RequestResponseBodyMethodProcessor:273||Using 'application/json', given [*/*] and supported [application/json, application/*+json, application/json, application/*+json] 2021-07-07 17:47:07.286|DEBUG|http-nio-8080-exec-1|o.s.w.s.m.m.annotation.RequestResponseBodyMethodProcessor:91||Writing [User{id=1, name='www'}] 2021-07-07 17:47:07.303|DEBUG|http-nio-8080-exec-1|org.springframework.web.servlet.DispatcherServlet:1131||Completed 200 OK