Spring/Spring boot

@PathVariable name 생략시 에러

챛채 2024. 8. 28. 15:53

프로젝트 도중

jakarta.servlet.ServletException: Request processing failed: 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와 @RequestParam 두 에노테이션에서 발생한다고 한다.

 

//작동 
 @GetMapping("/posts/{postId}")
    public PostResponse get(@PathVariable("postId") Long postId) {
        return postService.get(postId);
    }
    
//작동X
@GetMapping("/posts/{postId}")
	public PostResponse get(@PathVariable Long postId) {
    	return postService.get(postId);	
	}

 

해결방안

1. 애노테이션 이름 생략하지 않기(권장!!)

@RequestParam("username") String username
@PathVariable("userId") String userId

생략이 가능하다고는 하지만 이런 식으로 변수명을 지정해주는 것을 가장 권장한다.

 

2. 컴파일 시점 -parameters 옵션 적용

1. IntelliJ IDEA에서 File -> Settings를 연다. (Mac은 IntelliJ IDEA -> Settings)
2. Build, Execution, Deployment → Compiler → Java Compiler로 이동한다.
3. Additional command line parameters라는 항목에 다음을 추가한다. 

-parameters

4. out 폴더를 삭제하고 다시 실행한다. 꼭 out 폴더를 삭제해야 다시 컴파일이 일어난다.

 

3. 빌드 툴 Gradle 사용하기

1. IntelliJ IDEA에서 File -> Settings를 연다. (Mac은 IntelliJ IDEA -> Settings)
2. Build, Execution, Deployment → Build Tools → Gradle 로 이동한다.
3. run using에서 Gradle로 바꿀것

 

1, 2, 3번을 전부 실행해본 결과 2, 3번은 아직 이유를 발견하지 못했는데 오류를 잡지 못했다,,, 그래서 그냥 변수명 생략하지 않고 쓰는 습관 들이기로,,!!!