java spring如何实现代码干净的写法?
比如
package com.demo.controller;
public class DemoController {
public Object saveWithPost() {
return null;
}
public Object listWithGet() {
return null;
}
}
其实相当于
package com.demo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("demo")
public class DemoController {
@PostMapping(value = "save")
public Object saveWithPost() {
return null;
}
@GetMapping(value = "list")
public Object listWithGet() {
return null;
}
}
代码不需要手动处理就可以执行。
回复
1个回答

test
2024-06-19
所谓"干净"的写法得满足团队定制化规则进行编码.按照您给出的Demo. 我给出个人看法:可以利用面向切面的编程方式进行开发.编写相关切面.例如: 可以面向特定包进行切面 (com.demo.controller) 进行切面
- 捕获到尾缀包含 "Controller"的类进行处理,具体处理逻辑将按照您定制的编码规则进行调整.
- 类名去掉"Controller"然后进行lowercase.让后将其注入到springmvc中. (主要用于注入)
- 将方法名称按照"With"进行分割. 分割末位为对应的mvc get/post/put/delete等. 分割的首位为请求路径. 然后再依次注入为springmvc的具体请求. 具体的注入方式参考mvc的注入规则.
个人不推荐如此操作.除非团队有很强的协同能力. 对于不规范的命名规则和编码方式容易带来灾难性的后果.
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容