最佳代码练习,不要通过摘要在spring控制器中复制代码。
我有两个控制器,例如
@Controller
public class DoSomethingController {
private Entity helpfulMethod(Form form) {
Entity e = new Entity();
return e;
}
@PostMapping("/something")
public String something(Form form){
helpfulMethod(form);
}
}
@Controller
public class DoSomethingElseController {
private Entity helpfulMethod(Form form) {
Entity e = new Entity();
return e;
}
@PostMapping("/somethingElse")
public String somethingElse(Form form){
helpfulMethod(form);
}
}
如何使用abstractMethod并使用abstract从外部连接它们?
答案 0 :(得分:1)
我猜你需要为两个控制器引入一个超类
public abstract class BaseDoSomethingController {
protected Entity helpfulMethod(Form form) {
Entity e = new Entity();
return e;
}
}
让两个控制器都继承基类
@Controller
public class DoSomethingController extends BaseDoSomethingController {
@PostMapping("/something")
public String something(Form form){
helpfulMethod(form);
}
}
和第二个控制器相同