@AllArgsConstructor與@Value共同使用引發的報錯問題

加油吧丶學渣發表於2020-03-06

平時我們用lombok的方式來實現Bean的建構函式方式的注入,但是當遇到@Value註解的時候,就會出現問題,看下面這段程式碼:

@RestController
@AllArgsConstructor
@RequestMapping("test")
public class TestController {

    @Value("${test}")
    private String test;

    private TestService testService;

    @GetMapping()
    public String get() {
        System.out.println(test);
        return testService.get();
    }
}

啟動專案的時候,會丟擲異常


***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of constructor in com.good.base.controller.TestController required a bean of type 'java.lang.String' that could not be found.


Action:

Consider defining a bean of type 'java.lang.String' in your configuration.

如何解決這個問題呢?
其實很簡單,將AllArgsConstructor改成RequiredArgsConstructor,然後把需要注入的bean改成final型別的,就可以了

@RestController
@RequiredArgsConstructor
@RequestMapping("test")
public class TestController {

    @Value("${test}")
    private String test;

    private final TestService testService;

    @GetMapping()
    public String get() {
        System.out.println(test);
        return testService.get();
    }
}

 

相關文章