java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot3.3.0升级

SpringBoot3.3.0升级方案

作者:曼曼青青草

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

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

一、jdk17下载安装

1、下载

官网下载地址

Java Archive Downloads - Java SE 17

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

2、Jdk17项目环境设置

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

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

source和Dependencies均设置为jdk17

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

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

二、依赖升级

主要依赖升级和替换引入

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

1、Java17依赖升级

<properties>
<java.version>17</java.version>
<mybatis-plus.version>3.5.6</mybatis-plus.version>
<flowable.version>7.0.0</flowable.version>
</properties>
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <source>${java.version}</source>
                <target>${java.version}</target>
                <encoding>${project.build.sourceEncoding}</encoding>
            </configuration>
        </plugin>
    </plugins>
</build>

2、SpringBoot3.3.0依赖升级

<!-- SpringBoot的依赖配置-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-dependencies</artifactId>
    <version>3.3.0</version>
    <type>pom</type>
    <scope>import</scope>
</dependency>

3、mybatis-plus3.5.6依赖升级

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>${mybatis-plus.version}</version>
    <exclusions>
        <exclusion>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>3.0.3</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
</dependency>
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-core</artifactId>
    <version>3.5.6</version>
    <scope>compile</scope>
</dependency>

4、SpringSecurity6.3.0依赖升级

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-config</artifactId>
    <version>6.3.0</version>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-core</artifactId>
    <version>6.3.0</version>
</dependency>

5、Swagger.3.0依赖升级

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>6.1.8</version>
</dependency>
<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.3.0</version>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>
<!-- openAPI包,替换 Swagger 的 SpringFox -->
<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.3.0</version>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

6、jakarta包替换

<dependency>
    <groupId>jakarta.annotation</groupId>
    <artifactId>jakarta.annotation-api</artifactId>
</dependency>

7、其他

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-core</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
</dependency>
<dependency>
    <groupId>jakarta.validation</groupId>
    <artifactId>jakarta.validation-api</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
</dependency>

版本查看:

三、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主要区别

四、SpringSecurity6

1、拦截器变化

 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

七、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  #允许循环依赖

到此这篇关于SpringBoot3.3.0升级方案的文章就介绍到这了,更多相关SpringBoot3.3.0升级内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家! 

您可能感兴趣的文章:
阅读全文