如何防止从我的MongoRepository导出某些HTTP方法?

时间:2015-03-20 15:06:15

标签: spring spring-data spring-data-mongodb spring-data-rest

我使用spring-data-rest,我有一个像这样的MongoRepository:

@RepositoryRestResource
interface MyEntityRepository extends MongoRepository<MyEntity, String> {
}

我想允许GET方法但禁用PUT,POST,PATCH和DELETE(只读Web服务)。

根据http://docs.spring.io/spring-data/rest/docs/2.2.2.RELEASE/reference/html/#repository-resources.collection-resource,我应该能够这样做:

@RepositoryRestResource
interface MyEntityRepository extends MongoRepository<MyEntity, String> {

    @Override
    @RestResource(exported = false)
    public MyEntity save(MyEntity s);

    @Override
    @RestResource(exported = false)
    public void delete(String id);

    @Override
    @RestResource(exported = false)
    public void delete(MyEntity t);
}

它似乎无法正常工作,因为我仍然可以执行PUT,POST,PATCH和DELETE请求。

3 个答案:

答案 0 :(得分:38)

感谢Oliver,以下是覆盖的方法:

@RepositoryRestResource(collectionResourceRel = "people", path = "people")
public interface PersonRepository extends MongoRepository<Person, String> {

    // Prevents GET /people/:id
    @Override
    @RestResource(exported = false)
    public Person findOne(String id);

    // Prevents GET /people
    @Override
    @RestResource(exported = false)
    public Page<Person> findAll(Pageable pageable);

    // Prevents POST /people and PATCH /people/:id
    @Override
    @RestResource(exported = false)
    public Person save(Person s);

    // Prevents DELETE /people/:id
    @Override
    @RestResource(exported = false)
    public void delete(Person t);

}

答案 1 :(得分:2)

为什么不这样使用?

@Configuration
public class SpringDataRestConfiguration implements RepositoryRestConfigurer {

    @Override
    public void configureRepositoryRestConfiguration(RepositoryRestConfiguration restConfig) {
        restConfig.disableDefaultExposure();
    }
}

答案 2 :(得分:1)

这是迟来的回复,但是如果您需要阻止实体的全局http方法,请尝试使用它。

@Configuration
public class DataRestConfig implements RepositoryRestConfigurer {
    @Override
    public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
         config.getExposureConfiguration()
                .forDomainType(Person.class)
                .withItemExposure(((metdata, httpMethods) -> httpMethods.disable(HttpMethod.PUT, HttpMethod.POST, ... )))
                .withCollectionExposure((metdata, httpMethods) -> httpMethods.disable(HttpMethod.PUT, HttpMethod.POST, ...));
    }
}