2014-09-11 12 views
26

Hãy nói rằng tôi có hai kho:Tuỳ chỉnh đáp ứng cho yêu cầu gốc int Xuân REST của HATEOAS với cả RepositoryRestResource-s và bộ điều khiển thường xuyên

@RepositoryRestResource(collectionResourceRel = "person", path = "person") 
public interface PersonRepository extends PagingAndSortingRepository<Person, Long> { 
    List<Person> findByLastName(@Param("name") String name); 
} 

@RepositoryRestResource(collectionResourceRel = "person1", path = "person1") 
public interface PersonRepository1 extends PagingAndSortingRepository<Person1, Long> { 
    List<Person1> findByLastName(@Param("name") String name); 
} 

với một bộ điều khiển thông thường:

@Controller 
public class HelloController { 
    @RequestMapping("/hello") 
    @ResponseBody 
    public HttpEntity<Hello> hello(@RequestParam(value = "name", required = false, defaultValue = "World") String name) { 
     Hello hello = new Hello(String.format("Hello, %s!", name)); 
     hello.add(linkTo(methodOn(HelloController.class).hello(name)).withSelfRel()); 
     return new ResponseEntity<>(hello, HttpStatus.OK); 
    } 
} 

Hiện tại, phản hồi cho http://localhost:8080/ là:

{ 
    "_links" : { 
    "person" : { 
     "href" : "http://localhost:8080/person{?page,size,sort}", 
     "templated" : true 
    }, 
    "person1" : { 
     "href" : "http://localhost:8080/person1{?page,size,sort}", 
     "templated" : true 
    } 
    } 
} 

nhưng tôi muốn để có được một cái gì đó như thế này:

{ 
    "_links" : { 
    "person" : { 
     "href" : "http://localhost:8080/person{?page,size,sort}", 
     "templated" : true 
    }, 
    "person1" : { 
     "href" : "http://localhost:8080/person1{?page,size,sort}", 
     "templated" : true 
    }, 
    "hello" : { 
     "href" : "http://localhost:8080/hello?name=World" 
    } 
    } 
} 

Trả lời

29
@Component 
public class HelloResourceProcessor implements ResourceProcessor<RepositoryLinksResource> { 

    @Override 
    public RepositoryLinksResource process(RepositoryLinksResource resource) { 
     resource.add(ControllerLinkBuilder.linkTo(HelloController.class).withRel("hello")); 
     return resource; 
    } 
} 

dựa trên

1

Bạn cần có một ResourceProcessory cho tài nguyên Person của bạn đăng ký như một Bean. xem https://stackoverflow.com/a/24660635/442773

+2

Nhưng tôi không muốn thay đổi câu trả lời cho bất kỳ 'http: // localhost: 8080/person' , yêu cầu 'http: // localhost: 8080/person1' hoặc' http: // localhost: 8080/hello'. Tôi muốn thay đổi phản hồi được tạo tự động cho yêu cầu 'http: // localhost: 8080 /'. – jcoig

Các vấn đề liên quan