1

我正在使用Spring MVC 3.1创建一个RESTful API。我有一个唯一的数据库,所以我的 REST url必须包含,所以我知道要连接到哪个数据库。 ProjectCollectionProject

我已经习惯registerCustomEditor@InitBinder自动神奇地解决@PathVariable Project project (太棒了!)

但是现在我变得贪婪了,我想自动解决@PathVariable Collection collection而不是在这个控制器的每个动作中一遍又一遍地做同样的事情。问题在于,这Collection取决于Project得到解决。那么如何使用这种依赖项进行设置呢?

谢谢你的帮助!!

@Controller
@RequestMapping(value = "/project/{project}/collection", produces = {"application/json", "application/xml"})
public class CollectionController {

    private static final Logger log = LoggerFactory.getLogger(CollectionController.class);  

    @Autowired protected ProjectRepository projectRepository;
    @Autowired protected CollectionService collectionService;
    @Autowired protected PermissionService permissionService;

    @RequestMapping(method = RequestMethod.GET)
    public @ResponseBody List<CollectionResponse> query(@ActiveAccount Account account, @PathVariable Project project) {

        if (!permissionService.hasProjectAccess(account, project)) {
            throw new AccessDeniedException("Access Denied");
        }

        CollectionRepository collectionRepository = collectionService.getCollectionRepository(project);
        List<Collection> collections = collectionRepository.findByProjectId(project.getId());

        List<CollectionResponse> response = new ArrayList<>();
        for (Collection collection : collections) {
            response.add(new CollectionResponse(collection));
        }

        return response;
    }

    @RequestMapping(value = "/{collection}", method = RequestMethod.GET)
    public @ResponseBody CollectionResponse get(@ActiveAccount Account account, @PathVariable Project project, @PathVariable String collection) {

        if (!permissionService.hasProjectAccess(account, project)) {
            throw new AccessDeniedException("Access Denied");
        }

        CollectionRepository collectionRepository = collectionService.getCollectionRepository(project);

        return new CollectionResponse(collectionRepository.findOne(collection));
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Project.class, new PropertyEditorSupport() {

            @Override
            public String getAsText() {
                return ((Project) this.getValue()).getId();
            }

            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                setValue(projectRepository.findOne(text));
            }
        });
    }   

}
4

0 回答 0