@AllArgsConstructor與@Value共用的問題解決

時間無言_發表於2019-12-18

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

/**
 * @author sunhan
 */
@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();
    }
}

參考:
https://stackoverflow.com/questions/52321988/best-practice-for-value-fields-lombok-and-constructor-injection

相關文章