Spring Boot Java转Kotlin报错:如何修正RestTemplate相关@Bean方法?
修正Spring Boot Kotlin版CommandLineRunner Bean的问题
咱们先梳理下转换后代码的问题点,再给出对应的修正方案:
修正后的完整代码
@Bean fun run(restTemplate: RestTemplate): CommandLineRunner { return CommandLineRunner { args -> val quote = restTemplate.getForObject( "http://gturnquist-quoters.cfapps.io/api/random", Quote::class.java ) log.info(quote.toString()) } }
关键修正点说明
- 明确SAM转换类型:原代码直接返回Lambda时,Kotlin的类型推断偶尔会因上下文不够明确出现匹配错误。显式用
CommandLineRunner { ... }创建实例,能让编译器清晰识别这是实现了CommandLineRunner接口的对象,从根源避免类型不匹配的报错。 - 移除冗余的异常注解:CommandLineRunner接口的
run方法本身就声明了抛出Exception,Kotlin在处理该接口的SAM转换时会自动兼容异常声明,所以不需要在Bean方法上额外添加@Throws(Exception::class)。 - 确保日志对象可用:如果你的类还没初始化日志实例,记得补充日志相关的配置:
- 可以引入Lombok依赖,给类添加
@Slf4j注解自动生成log对象; - 或者手动初始化:
private val log = LoggerFactory.getLogger(javaClass)
- 可以引入Lombok依赖,给类添加
更简洁的写法(可选)
Kotlin支持更紧凑的函数式语法,你也可以直接返回符合CommandLineRunner签名的实例,代码更简洁:
@Bean fun run(restTemplate: RestTemplate) = CommandLineRunner { args -> val quote = restTemplate.getForObject( "http://gturnquist-quoters.cfapps.io/api/random", Quote::class.java ) log.info(quote.toString()) }
内容的提问来源于stack exchange,提问作者高万祥
相关产品推荐
相关产品推荐

