ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Spring - @PathVariable 사용 시 발생하는 오류 정리
    Spring 2025. 7. 4. 22:36
    반응형
    java.lang.IllegalArgumentException: Name for argument of type [java.lang.Long] not specified,
    and parameter name information not available via reflection.
    Ensure that the compiler uses the '-parameters' flag.

    🧨 오류 원인

    해당 오류는 @PathVariable에 이름을 생략했을 때, 파라미터 이름을 스프링이 인식하지 못해서 발생합니다.
    예를 들어, 다음 코드에서:

    @GetMapping("/{itemId}")
    public String getItem(@PathVariable Long itemId) {
        ...
    }

    @PathVariable의 name 혹은 value 속성이 생략되어 있고,
    동시에 Java 컴파일러가 파라미터 이름 정보를 포함하지 않았을 때
    Spring은 itemId라는 이름을 알 수 없으므로 예외를 던지게 됩니다.


    🔍 Java & Spring 버전에 따른 파라미터 이름 처리 방식

    Java 8 이상 -parameters 컴파일 옵션을 통해 파라미터 이름 정보를 .class에 저장 가능
    Spring 3.2 이상 파라미터 이름 정보를 읽어서 자동 매핑 가능 (단, -parameters 옵션 필요)
    Java 7 이하 or -parameters 옵션 미사용 파라미터 이름 정보를 읽을 수 없음 → 생략 불가능, 명시적으로 이름 지정해야 함

     

    ✅ 해결 방법

    방법 1. @PathVariable에 이름 명시하기 (안전한 방식)

    @GetMapping("/{itemId}")
    public String getItem(@PathVariable("itemId") Long id) {
        ...
    }

    항상 명시적으로 이름을 적어주면 자바 버전과 상관없이 동작합니다.


    방법 2. -parameters 옵션 추가 (생략 가능하게 만들기)

    Gradle의 경우 build.gradle에 다음 코드 추가:

    tasks.withType(JavaCompile) {
        options.compilerArgs << '-parameters'
    }

    Maven의 경우 pom.xml에 다음 설정 추가:

    <plugin>
      <artifactId>maven-compiler-plugin</artifactId>
      <configuration>
        <compilerArgs>
          <arg>-parameters</arg>
        </compilerArgs>
      </configuration>
    </plugin>

    적용 후 @PathVariable Long itemId 와 같이 생략해도 정상 작동합니다.

    반응형

    댓글

Designed by Tistory.