基于@AllArgsConstructor與@Value共用的問題解決
@AllArgsConstructor與@Value共用的問題解決
平時我們用lombok的方式來實現(xiàn)Bean的構(gòu)造函數(shù)方式的注入,但是當(dāng)遇到@Value注解的時候,就會出現(xiàn)問題,
看下面這段代碼
/**
* @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();
}
}
參考:這里
@AllArgsConstructor導(dǎo)致@value注入失敗
@AllArgsConstructor
@RestController
@RequestMapping("xx/xx" )
public class WxUserController extends BaseController {
private final WxUserService service;
private final PointsDetailService pointsDetailService;
private final WxUserPointsService wxUserPointsService;
@Value("${points.registerPoints}")
private int registerPoints;
................................
}
直接項目啟動失敗,報錯如下:
解決方法
本人是去掉@AllArgsConstructor,使用@autowired進(jìn)行注入,應(yīng)該還有別的方法可以解決這個沖突,我沒有試
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Spring Boot中優(yōu)雅的獲取yml文件工具類
今天小編就為大家分享一篇關(guān)于Spring Boot中優(yōu)雅的獲取yml文件工具類,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2018-12-12
Spring?Boot使用線程池處理上萬條數(shù)據(jù)插入功能
這篇文章主要介紹了Spring?Boot使用線程池處理上萬條數(shù)據(jù)插入功能,使用步驟是先創(chuàng)建一個線程池的配置,讓Spring Boot加載,用來定義如何創(chuàng)建一個ThreadPoolTaskExecutor,本文通過實例代碼給大家介紹的非常詳細(xì),需要的朋友參考下吧2022-08-08

