@AllArgsConstructor与@Value共用的问题解决
平时我们用lombok的方式来实现Bean的构造函数方式的注入,但是当遇到@Value注解的时候,就会出现问题,
看下面这段代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
/**
* @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类型的,就可以了
1
2
3
4
5
6
7
8
9
10
11
12
13
|
@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导致@value注入失败
1
2
3
4
5
6
7
8
9
10
11
|
@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进行注入,应该还有别的方法可以解决这个冲突,我没有试
以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/goodcto/article/details/103592721