AdSense

2026/9/1

Spring Boot Parameter 參數綁定問題

如果最近Spring Boot因為更新版本或改了一些依賴設定,而出現參數值為null或找不到的問題,原因如下。


Spring Boot 3.2.0開始,依賴的Spring Framework升級為6.1.x,而Spring Framework 6.1不再透過解析bytecode來推測參數名稱,如果編譯時沒有保留參數名稱,可能導致原來依靠參數名稱來注入/綁定對應資料的效果失效,所以可能進一步導致注入同型別bean時出現NoUniqueBeanDefinitionException dependency injection錯誤、@ConfigurationProperties properties binding錯誤、constructor binding錯誤、@RequestParam收不到參數、Swagger UI OpenAPI spec參數未出現等現象。


解決方式 一

在編譯時使用-parameters flag進行編譯,效果就是保留參數原名,這樣Spring Boot在reflection時就可以找到對應的參數名稱。

javac doc

-parameters
Generates metadata for reflection on method parameters. Stores formal parameter names of constructors and methods in the generated class file so that the method java.lang.reflect.Executable.getParameters from the Reflection API can retrieve them.


而在Spring Boot專案中通常依賴Maven Compiler Plugin進行編譯,透過在pom.xml中設定<parameters>true</parameters>如下來使用-parameters flag進行編譯。

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
        <parameters>true</parameters>
    </configuration>
</plugin>

解決方式 二

或是使用spring-boot-starter-parent如下,因為其提供預設的Maven Compiler Plugin有-parameters 。

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>4.1.1</version>
</parent>

沒有留言:

AdSense