degath
degath

Reputation: 1621

Abstract example in spring

Best code practice for not duplicate your code in spring controller by abstract.

I've got two controllers for example

@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);
    }
}

How to take helpfulMethod out and connect them from outside using abstract?

Upvotes: 0

Views: 31

Answers (1)

StanislavL
StanislavL

Reputation: 57381

I guess you need to introduce a super class for both the controllers

public abstract class BaseDoSomethingController {

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

and let both your controllers inherit the base class

@Controller
public class DoSomethingController extends BaseDoSomethingController {

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

and the same for the second controller

Upvotes: 1

Related Questions