当前位置: 首页 > news >正文

SpringBoot 2 最常用的配置汇总

        在 Spring Boot 项目中,有一些重要的配置需要关注,包括全局日期和时间格式的配置以及解决跨域问题的后端跨域配置,基本每个项目都是必须配置的,还有springboot配置文件必然也少不了配置数据库之类的,以下进行汇总列出,以方便需要时用到。

一、全局日期和时间格式配置

为项目配置全局日期和时间格式化yyyy-MM-dd HH:mm:ss,可以通过以下两种方式实现:

1 通过代码配置

 代码配置全局日期和时间格式化,如下:

/*** @author hua*/
@Configuration
public class WebConfiguration implements WebMvcConfigurer {/*** 项目全局时间格式化*/@Beanpublic ObjectMapper getObjectMapper() {// 创建ObjectMapper实例ObjectMapper om = new ObjectMapper();// 创建JavaTimeModule以支持Java 8的时间日期类型序列化和反序列化JavaTimeModule javaTimeModule = new JavaTimeModule();// 针对LocalDateTime类型,注册自定义的反序列化器,使用指定的日期时间格式进行反序列化javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));// 针对LocalDate类型,注册自定义的反序列化器,使用指定的日期格式进行反序列化javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));// 针对LocalTime类型,注册自定义的反序列化器,使用指定的时间格式进行反序列化javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern("HH:mm:ss")));// 将JavaTimeModule注册到ObjectMapper中,以启用对Java 8时间日期类型的支持om.registerModule(javaTimeModule);// 返回配置后的ObjectMapper对象return om;}
}
2 配置文件实现    

  在application.propertiesapplication.yml中进行配置:

# 设置日期格式
spring.jackson.date-format=yyyy-MM-dd# 设置时间格式
spring.jackson.time-format=HH:mm:ss# 设置日期时间格式
spring.jackson.date-time-format=yyyy-MM-dd HH:mm:ss

二、跨域配置

  在 SpringMVC 项目中,可以通过以下代码配置 CORS,处理跨域请求:

/*** @作者 hua* @描述 跨域配置*/
@Configuration
public class WebConfiguration implements WebMvcConfigurer {/*** 跨域配置对象* @return CorsConfiguration对象*/private CorsConfiguration corsConfig() {CorsConfiguration corsConfiguration = new CorsConfiguration();List<String> list = new ArrayList<>();// 允许所有来源list.add("*");// 设置允许的来源列表corsConfiguration.setAllowedOrigins(list);// 允许所有HeadercorsConfiguration.addAllowedHeader("*");// 允许所有方法(GET、POST等)corsConfiguration.addAllowedMethod("*");return corsConfiguration;}/*** 注册CORS过滤器* @return CorsFilter对象*/@Beanpublic CorsFilter corsFilter() {UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();// 对所有路径应用上面定义的CORS配置source.registerCorsConfiguration("/**", corsConfig());return new CorsFilter(source);}}

通过以上配置,可以解决 Vue 中出现的跨域问题,如错误提示 “has been blocked by CORS policy”。

拦截器配置

 在 Spring Boot 中,可以通过实现 HandlerInterceptor 接口来配置拦截器。

  1 先实现业务类,要拦截哪些请求怎么处理,以下是登陆token验证拦截实现如下:

/*** @author hua* @Description 拦截器* @date2019/5/29 */
public class TokenInterceptor extends HandlerInterceptorAdapter {@AutowiredSysLoginSessionServiceImpl sysLoginSessionService;@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception {String token=request.getHeader("user_token");if(token==null){if((request.getRequestURI()!=null&&request.getRequestURI().contains("/export/"))){return super.preHandle(request, response, handler);}else{WebUtil.response(response, RespUtil.respErr("请重新登陆!"));return false;}}SysLoginSession sysLoginSession=sysLoginSessionService.getByUserToken(token);if(sysLoginSession==null){WebUtil.response(response,RespUtil.respErr("session 失效,请重新登陆!"));return false;}request.setAttribute("user_id",sysLoginSession.getUserId());return true;}@Overridepublic void postHandle(HttpServletRequest request,HttpServletResponse response, Object handler,ModelAndView modelAndView) throws Exception {super.postHandle(request, response, handler, modelAndView);}@Overridepublic void afterCompletion(HttpServletRequest request,HttpServletResponse response, Object handler, Exception ex)throws Exception {super.afterCompletion(request, response, handler, ex);}

  实现 HandlerInterceptor 接口后,加入配置到配置项目交给springMvc容器管理。配置如下: 


/*** @author hua* @Description * @date 2019/5/29*/
@Configuration
public class WebConfiguration implements WebMvcConfigurer {@Beanpublic HandlerInterceptor getTokenInterceptor() {return new TokenInterceptor();}/*** 拦截器配置*/@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(getTokenInterceptor()).excludePathPatterns("/public/**").addPathPatterns("/backend/**");}}

application.yml配置文件

1. 日志配置

配置用于管理Spring Boot应用程序的日志输出。全局日志级别设置为INFO,而特定包com.example的日志级别为DEBUG。日志输出会记录到名为app.log的文件中。

logging:level:root: INFO  # 设置全局日志级别为INFOcom.example: DEBUG  # 针对包com.example设置日志级别为DEBUGfile:name: app.log  # 将日志输出到app.log文件

2. MySql数据库配置

  配置启用了HikariCP作为数据库连接池,并通过各种参数优化了数据库连接和缓存行为。

spring:datasource:url: jdbc:mysql://localhost:3306/dbname  # 数据库连接URL,连接到MySQLusername: root  # 数据库用户名password: 123456  # 数据库密码type: com.zaxxer.hikari.HikariDataSource  # 使用HikariCP作为数据源driver-class-name: com.mysql.cj.jdbc.Driver  # MySQL JDBC驱动类hikari:auto-commit: false  # 禁用自动提交connection-timeout: 30000  # 连接超时时间,30秒idle-timeout: 25000  # 空闲连接超时时间,25秒login-timeout: 5  # 登录超时时间,5秒max-lifetime: 30000  # 连接最大存活时间,30秒read-only: false  # 是否只读模式validation-timeout: 3000  # 验证连接超时时间,3秒maximum-pool-size: 15  # 最大连接池大小为15minimum-idle: 10  # 最小空闲连接数为10data-source-properties:cachePrepStmts: true  # 启用预编译语句缓存prepStmtCacheSize: 250  # 预编译语句缓存大小prepStmtCacheSqlLimit: 2048  # 单个预编译语句的SQL大小限制useServerPrepStmts: true  # 使用服务器端预编译语句useLocalSessionState: true  # 使用本地会话状态rewriteBatchedStatements: true  # 重写批处理语句以提高性能cacheResultSetMetadata: true  # 缓存结果集元数据cacheServerConfiguration: true  # 缓存服务器配置elideSetAutoCommits: true  # 优化跳过setAutoCommit调用maintainTimeStats: false  # 关闭时间统计以提升性能

3. PostgreSQL 数据库配置

spring:datasource:url: jdbc:postgresql://localhost:5432/mydb2username: postgres2password: password2

4. redis数据库配置

 使用redis作为内存数据库:

redis:host: xx.xx.xx.xx  # Redis服务器的IP地址password: xxxxx  # Redis服务器的密码port: 6379  # Redis服务器的端口号,默认6379jedis:pool:max-active: 1000  # 最大活跃连接数max-wait: 1000ms  # 获取连接的最大等待时间max-idle: 1000  # 连接池中最大空闲连接数min-idle: 1000  # 连接池中最小空闲连接数database: 2  # 使用的Redis数据库索引,默认为0timeout: 15000  # Redis连接超时时间,单位为毫秒

Redis连接参数,包括Jedis连接池配置、服务器地址、密码、端口、数据库索引等。

5. 缓存配置

spring:cache:type: caffeine  # 使用Caffeine作为缓存实现caffeine:spec: maximumSize=1000,expireAfterWrite=5m  # 缓存最大容量为1000条,缓存条目在写入后5分钟过期

配置使用Caffeine作为缓存实现,并设置缓存的最大容量为1000条记录,缓存条目在写入5分钟后过期。Caffeine是一种高性能的本地缓存库,支持多种缓存过期和回收策略。

 使用缓存代码:

@EnableCaching
@SpringBootApplication
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}
}@Service
public class UserService {@Cacheable("users")public User findUserById(Long id) {// 查询数据库操作}
}
在Spring Boot中使用缓存配置步骤:
  1. 开启缓存:在主应用类上添加 @EnableCaching 注解。
  2. 配置缓存类型:通过 spring.cache.type 指定缓存类型,如 simpleehcachecaffeine 等。
  3. 缓存注解
  • @Cacheable: 用于缓存方法的返回值。
  • @CachePut: 更新缓存。
  • @CacheEvict: 清除缓存。

缓存的持续时间和失效策略取决于你所使用的缓存类型及其配置。

  • 默认缓存 (simple):Spring Boot的simple缓存是基于ConcurrentHashMap实现的,默认情况下,缓存不会自动过期,数据会一直保存在缓存中直到应用重启或显式清除。

  • 高级缓存(如EhcacheCaffeine):这些缓存提供了更复杂的配置,可以通过TTL(Time To Live)或TTR(Time To Refresh)设置缓存的失效时间。例如,Caffeine支持基于时间的缓存过期、基于访问频率的过期等。

 

6. 服务器配置

  springboot服务配置:

server:port: 8080tomcat:max-threads: 200 # tomcat最大线程数connection-timeout: 10000 # 连接超时时间max-connections: 1000 # 最大连接数max-http-header-size: 2MB # 最大请求头context-path: /app

7.定时任务

spring:task:scheduling:pool:size: 12  # 定时任务线程池的大小为 12,用于控制同时执行的定时任务数量。

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • SpringBoot + Vue实现websocket
  • Javascript归纳与总结——this指向及其改变、new关键字与原型链、异步、闭包和函数防抖与节流
  • Python 全栈系列265 使用ORM、Kafka、Apscheduler实现任务的并发处理
  • 基于django的失物招领系统的设计与实现/ 基于Python的失物招领系统的设计与实现/失物招领管理系统
  • Linux随记(十一)
  • Android13系统源码内置App并通过AIDL调用获取内置存储卡的真实大小
  • EmbeddedGUI简介
  • 语音控制开关的语音识别ic芯片方案
  • Linux信号处理机制基础
  • 创新之光闪耀,点赋科技在第十三届创新创业大赛中绽放光彩
  • BaseCTF Week2
  • linux固定ip
  • Tampermonkey 安装
  • Python的8个构建桌面应用的技巧
  • CNN网络的一些基本知识
  • angular2 简述
  • CentOS 7 防火墙操作
  • centos安装java运行环境jdk+tomcat
  • interface和setter,getter
  • maven工程打包jar以及java jar命令的classpath使用
  • Python爬虫--- 1.3 BS4库的解析器
  • vue的全局变量和全局拦截请求器
  • 基于webpack 的 vue 多页架构
  • 嵌入式文件系统
  • 山寨一个 Promise
  • 使用SAX解析XML
  • 一道闭包题引发的思考
  • 源码之下无秘密 ── 做最好的 Netty 源码分析教程
  • 7行Python代码的人脸识别
  • 基于django的视频点播网站开发-step3-注册登录功能 ...
  • #Linux(帮助手册)
  • #数据结构 笔记三
  • (23)Linux的软硬连接
  • (3)Dubbo启动时qos-server can not bind localhost22222错误解决
  • (7)摄像机和云台
  • (PHP)设置修改 Apache 文件根目录 (Document Root)(转帖)
  • (附表设计)不是我吹!超级全面的权限系统设计方案面世了
  • (附源码)springboot优课在线教学系统 毕业设计 081251
  • (七)Knockout 创建自定义绑定
  • (三)终结任务
  • (五)MySQL的备份及恢复
  • (一)SpringBoot3---尚硅谷总结
  • (转)【Hibernate总结系列】使用举例
  • .Net Attribute详解(上)-Attribute本质以及一个简单示例
  • .NET CORE 3.1 集成JWT鉴权和授权2
  • .Net的DataSet直接与SQL2005交互
  • .NET是什么
  • /proc/interrupts 和 /proc/stat 查看中断的情况
  • /使用匿名内部类来复写Handler当中的handlerMessage()方法
  • @column注解_MyBatis注解开发 -MyBatis(15)
  • [ 隧道技术 ] 反弹shell的集中常见方式(二)bash反弹shell
  • [.NET 即时通信SignalR] 认识SignalR (一)
  • [AI 大模型] 百度 文心一言
  • [bzoj2957]楼房重建
  • [CakePHP] 在Controller中使用Helper