掘金 后端 ( ) • 2024-05-11 15:00

一、事情起因:

假如你也和我一样,正在为屎山代码进行重构,也许这个技巧能够帮助你提效。

我正在为了一个查找替换的问题发愁,一个历史的代码没有明确写出@RequestParam里面的name属性,导致我在执行新版本代码时出现了异常。

在升级完Springboot3.0及相关一系列框架版本以后,天真以为技术到家一把梭哈,可是殊不知一个问题让我困顿了一会儿,那就是:

Caused by: java.lang.IllegalStateException: RequestParam.value() was empty on parameter 0 of method queryBuildingFloorRoomExpandByRoomId 
at feign.Util.checkState(Util.java:140) 
at org.springframework.cloud.openfeign.annotation.RequestParamParameterProcessor.processArgument(RequestParamParameterProcessor.java:63) 
at org.springframework.cloud.openfeign.support.SpringMvcContract.processAnnotationsOnParameter(SpringMvcContract.java:298) 
at feign.Contract$BaseContract.parseAndValidateMetadata(Contract.java:126) 
...

不要着急,这的确个小问题,但是我这次研究的是如何高效的“一键修复”这个问题。

第一眼看起来,其实也很简单,但是再仔细一看,我的天啊,整个祖传代码要改动的服务超过20+、代码行数多到滚动条都剩下一个小点了,难道我要一个个Find & replace吗?

那不是我们聪明的开发者应该做的事情,于是我开始想办法解决它。

二、解决过程:

开始,正式解决问题。

步骤一:

我悄悄打开Copilot,开始问它:

你好,Copilot :

How can I batch replace "@RequestParam Long companyId" with @RequestParam("companyId") Long companyId

它莫名其妙的回复了我一顿,反正不是我想要的,我都懒得粘贴结果了,反正错了。

接着,我再问了一下:

batch replace "@RequestParam Long ." with @RequestParam(".") Long .\*

步骤二

这一次,它给了我一个打开的钥匙,虽然不完全对,但是我已经知道怎么干了:

To batch replace @RequestParam Long anyname with @RequestParam("anyname") Long anyname in your code, you can use the Find and Replace feature in your IDE (IntelliJ IDEA 2024.1.1). However, this requires a regular expression to match any variable name. Here are the steps:

Open the Find and Replace dialog box. You can do this by going to Edit -> Find -> Replace or by using the shortcut Ctrl + R on Windows/Linux or Cmd + R on macOS.

In the Find field, enter @RequestParam Long (\w+). Make sure to check the Regex checkbox to enable regular expression.

In the Replace with field, enter @RequestParam("$1") Long $1.

Click on Replace All.

Please note that this will replace all occurrences in the currently open file. If you want to replace in the entire project, use Replace in Path instead of Replace. This regular expression (\w+) matches any word character (equal to \[a-zA-Z0-9\_]) between @RequestParam Long and the end of the line. The parentheses create a group, which is referenced in the replacement as \$1.

步骤三

最后,我自己小改了一下,形成了一个可行的方案:

具体如下

查找:@RequestParam (\w+) (\w+)

替换:@RequestParam("$2") $1 \$2

在伟大的IDEA里面一执行,结果如下的Tips所示,完全符合(💯)我的预期,这个问题就这么解决了。

截屏2024-05-11 14.19.14.png

最后,当然是Replace All ,然后整体编译,再运行了,解决了!

写在最后

有时候解决问题,可以用的手段很多,只是现在又多了AI一个,我始终坚信它会是你编程路上的一个聪明的小伙伴,不要担心它会替代你,因为它永远不会替代你,只会让你不用记住不该记住的,专注于自己的业务问题。和它一起思考,它未必会直接给出你一个100分的答案,但是它却可以通过不同的方式让你得到正确的结果,比如我上面那个例子,它也没有直接给出我可以直接复制粘贴的答案,但是通过它给出的例子,我直接就推出了正确答案,这比去百度、谷歌,然后再海量的信息里面遨游,可不是很巴适?