Golam Mazid Sajib
Golam Mazid Sajib

Reputation: 9457

Spring request mapping not working when specified in interface

I write request mapping at interface but it's not working.

Request / response body POJOs:

public class ReqAa {
    private String firstValue;
    private String secondValue;

    public String getFirstValue() {
        return firstValue;
    }

    public ReqAa setFirstValue(String firstValue) {
        this.firstValue = firstValue;
        return this;
    }

    public String getSecondValue() {
        return secondValue;
    }

    public ReqAa setSecondValue(String secondValue) {
        this.secondValue = secondValue;
        return this;
    }
}

public class RespAa{
    private String status;

    RespAa(String status){
        this.status = status;
    }

    public String getStatus() {
        return status;
    }

    public RespAa setStatus(String status) {
        this.status = status;
        return this;
    }
}

Interfaces:

public interface A{
    interface Aa{
        @PostMapping("/do/something")
        RespAa doSomething(@RequestBody ReqAa);
    }

    interface Ab{
        @PostMapping("/do/another")
        RespAb doAnother(@RequestBody ReqAb);
    }

}

@PreAuthorize("hasAuthority('admin')")
@RequestMapping("/api/admin")
public interface IClient extends A.Aa{
}

Rest Controller:

@RestController
public class Client implements IClient{
    @Override
    public RespAa doSomething(ReqAa reqAa) {
        return new RespAa("SUCCESS");
    }
}

Spring boot @RequestBody could not mapping as Body. Its took it as parameter.

Example:

generated request: /api/admin/do/something?firstValue=fv&secondValue=sv

expected mapping: /api/admin/do/something

requestBody: { "firstValue":"fv","secondValue":"sv"}

its work when i used @RequestBody in implementaion method.

@RestController
public class Client implements IClient{
    @Override
    public RespAa doSomething(@RequestBody ReqAa reqAa) {
        return new RespAa("SUCCESS");
    }
}

I used spring boot version: 1.5.10.

Upvotes: 2

Views: 1504

Answers (1)

Golam Mazid Sajib
Golam Mazid Sajib

Reputation: 9457

I solved my problem using interface default method. Working code here:

Interfaces:

public interface A{
    interface Aa{

        RespAa doSomething(ReqAa);

        @PostMapping("/do/something")
        default RespAa dDoSomething(@RequestBody ReqAa){
            return doSomething(ReqAa);
        }

    }

    interface Ab{
        @PostMapping("/do/another")
        RespAb doAnother(@RequestBody ReqAb);
    }

}

@PreAuthorize("hasAuthority('admin')")
@RequestMapping("/api/admin")
public interface IClient extends A.Aa{
}

Rest Controller:

@RestController
public class Client implements IClient{
    @Override
    public RespAa doSomething(ReqAa reqAa) {
        return new RespAa("SUCCESS");
    }
}

Upvotes: 2

Related Questions