xxx required a bean of type ‘java.lang.Integer‘ that could not be found
日志
2022-11-03 13:15:38.189 ERROR 8384 --- [] [ main] o.s.b.d.LoggingFailureAnalysisReporter 40 :
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 1 of constructor in com.cgws.fintech.fundmall.bizfund.mutual.controller.LcscExternalProvideController required a bean of type 'java.lang.Integer' that could not be found.
Action:
Consider defining a bean of type 'java.lang.Integer' in your configuration.
Process finished with exit code 1
源代码如下:
@Slf4j
@RestController
@RequestMapping(value = "/xxx")
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class LcscExternalProvideController {
private final LcscExternalProvideService lcscExternalProvideService;
@Value("${constants.request.fundCode.maxSize:30}")
private final Integer maxSize;
}
我使用Lombok
的@RequiredArgsConstructor
构造注入替换@Autowired
注入,然后使用@Value
给maxSize
变量赋值,但启动项目的时候就报上面的异常,说找不到java.lang.Integer
类型的bean
???
再看Lombok
生成的构造函数
构造函数里面确实包含有Integer
类型,因为@RequiredArgsConstructor
注解会检查被final
修改的字段,非final
修饰的字段不会被包含在构造函数里初始化注入bean
。
解决
删除maxSize
变量的final
修饰符,这样就不会被检查
@Slf4j
@RestController
@RequestMapping(value = "/xxx")
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class LcscExternalProvideController {
private final LcscExternalProvideService lcscExternalProvideService;
@Value("${constants.request.fundCode.maxSize:30}")
private Integer maxSize;
}
再看构造函数,此时没有包含Integer
项目启动也正常,maxSize也获取到值
扩展
Lombok还有一个@AllArgsConstructor
构造注解,使用该注解不管是否final
修饰的成员变量都会被注入,所以@AllArgsConstructor
和@Value
不能同时使用
onConstructor
属性值:
onConstructor_ = {@Autowired}
onConstructor = @_(@Autowired)