平时我们用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();
}
}