2017-11-29 3 views
0

봄 컨트롤러에서 코드를 중복 작성하지 않는 최상의 코드 연습.봄의 추상 예제

나는 예를 들어 두 개의 컨트롤러

@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을 꺼내 외부 추상적를 사용하여 그들을 연결하는있어?

답변

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

두 번째 컨트롤러에 대해 동일한을 상속 할 필요가 생각