spring 中的抽象示例

Abstract example in spring

不通过抽象在 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);
    }
}

如何将 helpfulMethod 取出并使用抽象从外部连接它们?

我猜你需要为两个控制器引入一个超级class

public abstract class BaseDoSomethingController {

    protected Entity helpfulMethod(Form form) {
        Entity e = new Entity();
        return e;
    }
}

并让您的两个控制器都继承基础 class

@Controller
public class DoSomethingController extends BaseDoSomethingController {

    @PostMapping("/something")
    public String something(Form form){
        helpfulMethod(form);
    }
}

第二个控制器也一样