SpringBoot 2 最常用的配置汇总

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

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

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

1 通过代码配置

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

java 复制代码
/**
 * @author hua
 */
@Configuration
public class WebConfiguration implements WebMvcConfigurer {

    /**
     * 项目全局时间格式化
     */
    @Bean
    public 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,处理跨域请求:

java 复制代码
/**
 * @作者 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);

        // 允许所有Header
        corsConfiguration.addAllowedHeader("*");

        // 允许所有方法(GET、POST等)
        corsConfiguration.addAllowedMethod("*");

        return corsConfiguration;
    }

    /**
     * 注册CORS过滤器
     * @return CorsFilter对象
     */
    @Bean
    public 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验证拦截实现如下:

java 复制代码
/**
 * @author hua
 * @Description 拦截器
 * @date2019/5/29 
 */
public class TokenInterceptor extends HandlerInterceptorAdapter {

   @Autowired
   SysLoginSessionServiceImpl sysLoginSessionService;

    @Override
    public 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;

    }


    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }

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

java 复制代码
/**
 * @author hua
 * @Description 
 * @date 2019/5/29
 */
@Configuration
public class WebConfiguration implements WebMvcConfigurer {


    @Bean
    public HandlerInterceptor getTokenInterceptor() {
        return new TokenInterceptor();
    }


    /**
     * 拦截器配置
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        registry.addInterceptor(getTokenInterceptor())
                .excludePathPatterns("/public/**")
                .addPathPatterns("/backend/**");

    }

}

四**、** application.yml配置文件

1. 日志配置

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

java 复制代码
logging:
  level:
    root: INFO  # 设置全局日志级别为INFO
    com.example: DEBUG  # 针对包com.example设置日志级别为DEBUG
  file:
    name: app.log  # 将日志输出到app.log文件

2. MySql数据库配置

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

java 复制代码
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/dbname  # 数据库连接URL,连接到MySQL
    username: 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  # 最大连接池大小为15
      minimum-idle: 10  # 最小空闲连接数为10
      data-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 数据库配置

java 复制代码
spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/mydb2
    username: postgres2
    password: password2

4. redis数据库配置

使用redis作为内存数据库:

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

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

5. 缓存配置

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

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

使用缓存代码:

java 复制代码
@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服务配置:

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

7.定时任务

java 复制代码
spring:
  task:
    scheduling:
      pool:
        size: 12  # 定时任务线程池的大小为 12,用于控制同时执行的定时任务数量。
相关推荐
极客先躯几秒前
java和kotlin 可以同时运行吗
android·java·开发语言·kotlin·同时运行
白总Server37 分钟前
MySQL在大数据场景应用
大数据·开发语言·数据库·后端·mysql·golang·php
luoluoal1 小时前
java项目之企业级工位管理系统源码(springboot)
java·开发语言·spring boot
ch_s_t1 小时前
新峰商城之购物车(一)
java·开发语言
蜜桃小阿雯1 小时前
JAVA开源项目 校园美食分享平台 计算机毕业设计
java·jvm·spring boot·spring cloud·intellij-idea·美食
黄昏_1 小时前
苍穹外卖Day01-2
java·spring
努力的八爪鱼1 小时前
记录工作中遇到的问题(持续更新~)
java
求学小火龙1 小时前
ElasticSearch介绍+使用
java·大数据·elasticsearch
mikey棒棒棒1 小时前
算法练习题25——合并多项式
java·算法·hashmap·哈希·多项式
kimloner1 小时前
工厂模式(二):工厂方法模式
java·设计模式·工厂方法模式