SpringBoot3.3.0升级方案

07-17 1738阅读

      本文介绍了由SpringBoot2升级到SpringBoot3.3.0升级方案,新版本的升级可以解决旧版本存在的部分漏洞问题。

一、jdk17下载安装

1、下载

官网下载地址

Java Archive Downloads - Java SE 17

SpringBoot3.3.0升级方案

SpringBoot3.3.0升级方案

SpringBoot3.3.0升级方案

Jdk17下载后,可不设置系统变量java_home,仅在idea的指定项目中设置即可。

2、Jdk17项目环境设置

a).File-->Settings-->Build,Execution,Deployment-->Compiler-->Java Compiler

SpringBoot3.3.0升级方案

b).File-->Project Settings-->modules

source和Dependencies均设置为jdk17

SpringBoot3.3.0升级方案

SpringBoot3.3.0升级方案

SpringBoot3.3.0升级方案

c).File-->Plateform Settings-->SDKS

SpringBoot3.3.0升级方案

d).启动类Edit Configuration-->Run/Debug Configurations

SpringBoot3.3.0升级方案

二、依赖升级

主要依赖升级和替换引入

Java17 && Spring3.3.0 && mybatis-plus3.5.6 && Spring Security6.3.0 && Swagger3 && jakarta  &&maven3.6

1、Java17依赖升级

17
3.5.6
7.0.0

    
        
            org.apache.maven.plugins
            maven-compiler-plugin
            3.1
            
                ${java.version}
                ${java.version}
                ${project.build.sourceEncoding}
            
        
    

2、SpringBoot3.3.0依赖升级


    org.springframework.boot
    spring-boot-dependencies
    3.3.0
    pom
    import

3、mybatis-plus3.5.6依赖升级

    com.baomidou
    mybatis-plus-boot-starter
    ${mybatis-plus.version}
    
        
            org.mybatis
            mybatis-spring
        
    


    org.mybatis
    mybatis-spring
    3.0.3
    org.springframework
    spring-web


    com.baomidou
    mybatis-plus-core
    3.5.6
    compile

4、SpringSecurity6.3.0依赖升级

    org.springframework.security
    spring-security-config
    6.3.0


    org.springframework.security
    spring-security-core
    6.3.0

5、Swagger.3.0依赖升级

    org.springframework
    spring-webmvc
    6.1.8


    org.springdoc
    springdoc-openapi-starter-webmvc-ui
    2.3.0


    org.projectlombok
    lombok

    org.springdoc
    springdoc-openapi-starter-webmvc-ui
    2.3.0


    org.springframework.boot
    spring-boot-starter-web


    org.projectlombok
    lombok
    true


    org.springframework.boot
    spring-boot-starter-test
    test

6、jakarta包替换

    jakarta.annotation
    jakarta.annotation-api

7、其他

    org.springframework
    spring-context-support


    org.springframework.security
    spring-security-core


    org.springframework
    spring-web


    jakarta.validation
    jakarta.validation-api


    org.apache.commons
    commons-lang3


    com.fasterxml.jackson.core
    jackson-annotations


    org.springframework
    spring-tx


    org.springframework
    spring-tx

版本查看:

 mvn -version

java -version

三、Swagger3.0升级(OpenAPI)

1、配置文件

OpenAPIConfig.java

package com.inspur.web.core.config;
import io.swagger.v3.oas.models.ExternalDocumentation;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
 * @author: Inspur
 * @datetime: 2024/3/26
 * @desc:
 */
@Configuration
public class OpenAPIConfig {
    @Bean
    public OpenAPI openAPI() {
        return new OpenAPI()
                .info(new Info()
                        .title("接口文档标题")
                        .description("SpringBoot3 集成 Swagger3接口文档")
                        .version("v1"))
                .externalDocs(new ExternalDocumentation()
                        .description("项目API文档")
                        .url("/"));
    }
}

2、使用示例

SwaggerController.java

import io.swagger.v3.oas.annotations.Hidden;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;
/**
 * @author: zjl
 * @datetime: 2024/3/26
 * @desc:
 */
@Tag(name = "控制器:测试Swagger3", description = "描述:测试Swagger3")
@RestController
public class SwaggerController {
    @Operation(summary = "测试Swagger3注解方法Get")
    @Parameters({@Parameter(name = "id",description = "编码"),
            @Parameter(name = "headerValue",description = "header传送内容")})
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "请求成功"),
            @ApiResponse(responseCode = "400", description = "请求参数没填好"),
            @ApiResponse(responseCode = "401", description = "没有权限"),
            @ApiResponse(responseCode = "403", description = "禁止访问"),
            @ApiResponse(responseCode = "404", description = "请求路径没有或页面跳转路径不对")
    })
    @GetMapping(value = "/swagger/student")
    public Object getStudent(@RequestParam @Parameter(example = "2")  String id,
                             @RequestHeader @Parameter(example = "2") String headerValue){
        return id;
    }
    @Operation(summary = "测试Swagger3注解方法Post")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "请求成功"),
            @ApiResponse(responseCode = "400", description = "请求参数没填好"),
            @ApiResponse(responseCode = "401", description = "没有权限"),
            @ApiResponse(responseCode = "403", description = "禁止访问"),
            @ApiResponse(responseCode = "404", description = "请求路径没有或页面跳转路径不对")
    })
    @PostMapping(value = "/swagger/student", produces = "application/json")
    public SwaggerApiModel updateStudent(@RequestBody SwaggerApiModel model){
        return model;
    }
    /**
     * swagger 不暴漏该 api,通过@Hidden隐藏
     * 但是仍然可以访问
     * @return
     */
    @Hidden
    @GetMapping(value = "/swagger/hiddenApi")
    public String hiddenApi(){
        return "hiddenApi";
    }
    /**
     * swagger 暴漏该 api,没有配置@Hidden会展示
     * @return
     */
    @GetMapping(value = "/swagger/noHiddenApi")
    public String noHiddenApi(){
        return "noHiddenApi";
    }
}

3、swagger2和swagger3主要区别

SpringBoot3.3.0升级方案

四、SpringSecurity6

1、拦截器变化

SpringBoot3.3.0升级方案

 extends HandlerInterceptorAdapter

==>

implements HandlerInterceptor

自定义拦截器

implements WebMvcConfigurer

==>

extends WebMvcConfigurationSupport

跨域配置eg:ResourceConfig.java:

addAllowedOrigin ==>

addAllowedOriginPattern

@Configuration
public class ResourcesConfig implements WebMvcConfigurer
{
@Bean
public CorsFilter corsFilter()
{
// 设置访问源地址
// config.addAllowedOrigin("*");
config.addAllowedOriginPattern("*");
}
}

2、过滤器变化

antMatchers ==> requestMatchers

匹配地址时 “**”==> “*”

示例:

Spring2:

public class SecurityConfig extends WebSecurityConfigurerAdapter
{
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception
{
    return super.authenticationManagerBean();
}

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception
{
    httpSecurity
            // CSRF禁用,因为不使用session
            .csrf().disable()
            // 认证失败处理类
            .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
            // 基于token,所以不需要session
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
            // 过滤请求
            .authorizeRequests()
            // 对于登录login 注册register 验证码captchaImage 允许匿名访问
            .antMatchers("/login","/loginApp", "/appLogin","/register", "/captchaImage","/factory/getPublicKey").anonymous()
            .antMatchers(
                    HttpMethod.GET,
                    "/",
                    "/*.html",
                    "/**/*.html",
                    "/**/*.css",
                    "/**/*.js",
                    "/profile/**"
            ).permitAll()
            .antMatchers("/common/download**").anonymous()
        // 除上面外的所有请求全部需要鉴权认证
        .anyRequest().authenticated()
        .and()
        .headers().frameOptions().disable();
httpSecurity.logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler);
// 添加JWT filter
httpSecurity.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
// 添加CORS filter
httpSecurity.addFilterBefore(corsFilter, JwtAuthenticationTokenFilter.class);
httpSecurity.addFilterBefore(corsFilter, LogoutFilter.class);
}
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception
    {
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
    }
}

/**
 * 强散列哈希加密实现
 */
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder()
{
    return new BCryptPasswordEncoder();
}
}

Spring3:

@Configuration
@EnableWebSecurity
@AllArgsConstructor
@EnableMethodSecurity
public class SecurityConfig
{
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
    return authenticationConfiguration.getAuthenticationManager();
}

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
            // CSRF禁用,因为不使用session
            .csrf().disable()
            // 禁用HTTP响应标头
            .headers().cacheControl().disable().and()
            // 认证失败处理类
            .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
            // 基于token,所以不需要session
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
            // 过滤请求
            .authorizeRequests()
            // 对于登录login 注册register 验证码captchaImage 允许匿名访问
            //                // 对于登录login 注册register 验证码captchaImage 允许匿名访问
            .requestMatchers("/login","/loginApp", "/appLogin","/register", "/captchaImage","/factory/getPublicKey").anonymous()
            .requestMatchers(
                    HttpMethod.GET,
                    "/",
                    "/*.html",
                    "/*/*.html",
                    "/*/*.css",
                    "/*/*.js",
                    "/profile/**"
            ).permitAll()
            .requestMatchers("/common/download**").anonymous()
        // 除上面外的所有请求全部需要鉴权认证
        .anyRequest().authenticated()
        .and()
        .headers().frameOptions().disable();
// 添加Logout filter
http.logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler);
// 添加JWT filter
http.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
// 添加CORS filter
http.addFilterBefore(corsFilter, JwtAuthenticationTokenFilter.class);
http.addFilterBefore(corsFilter, LogoutFilter.class);
}
/**
 * 强散列哈希加密实现
 */
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder()
{
    return new BCryptPasswordEncoder();
}

}

五、Maven3.6

六、javax替换 Jakarta

批量替换:

javax.persistence.*   -> jakarta.persistence.*

javax.validation.*    -> jakarta.validation.*

javax.servlet.*       -> jakarta.servlet.*

javax.annotation.*    -> jakarta.annotation.*

javax.transaction.*   -> jakarta.transaction.*

import javax.  ==>  import jakarta.

或者使用idea工具:Refactor==>Migrate

SpringBoot3.3.0升级方案

七、controller请求地址问题

对于GetMapping方法,@PathVariable(“roleId”) 需要注明变量名

public AjaxResult getInfo(@PathVariable Long roleId)

==>

public AjaxResult getInfo(@PathVariable("roleId") Long roleId)

八、配置文件修改

# swagger3
spring:
  mvc:
      pathmatch:
      matching-strategy: ant_path_matcher
# 升级后可能导致不支持Bean的注入依赖,可以在配置文件解决
  main:
    allow-circular-references: true  #允许循环依赖

VPS购买请点击我

文章版权声明:除非注明,否则均为主机测评原创文章,转载或复制请以超链接形式并注明出处。

目录[+]