我有以下REST存储库,其实现由Spring在运行时生成.
@RepositoryRestResource
public interface FooRepository extends CrudRepository<Foo, Long> {
}
Run Code Online (Sandbox Code Playgroud)
这意味着我将通过REST提供save(),find(),exists()和其他可用方法.
现在,我想覆盖其中一个方法; 例如,save().为此,我将创建一个暴露该方法的控制器,如下所示:
@RepositoryRestController
@RequestMapping("/foo")
public class FooController {
@Autowired
FooService fooService;
@RequestMapping(value = "/{fooId}", method = RequestMethod.PUT)
public void updateFoo(@PathVariable Long fooId) {
fooService.updateProperly(fooId);
}
}
Run Code Online (Sandbox Code Playgroud)
问题: 如果我启用了这个控制器,那么Spring实现的所有其他方法都不再暴露.因此,例如,我不能再对/ foo/1执行GET请求
问题: 是否有一种覆盖REST方法的方法,同时仍保留其他自动生成的Spring方法?
额外信息:
这个问题看起来非常相似: Spring Data Rest:RestController中的覆盖方法具有相同的请求映射路径 ......但我不想将路径更改为/ foo/1/save之类的东西
我想过使用@RepositoryEventHandler,但我不是很喜欢这个想法,因为我想把它封装在一个服务之下.此外,您似乎失去了对事务上下文的控制.
有时您可能希望为特定资源编写自定义处理程序.要利用Spring Data REST的设置,消息转换器,异常处理等,请使用@RepositoryRestController注释而不是标准的Spring MVC @Controller或@RestController
所以它似乎应该开箱即用,但不幸的是没有.
我在应用程序上使用Spring Boot(1.3.3)和基于注释的/ JavaConfig配置.我有以下存储库接口:
@RepositoryRestResource(collectionResourceRel = "something", path = "something")
public interface SomethingRepository
extends CrudRepository<SomethingRepository, Long> {
}
Run Code Online (Sandbox Code Playgroud)
我想要做的是覆盖生成的存储库代理中的某些方法的行为.我发现这样做是基于什么文档建议添加新的自定义方法的唯一方法(参见:添加自定义行为,单库),所以我定义如下界面:
public interface SomethingRepositoryCustom {
Something findOne(Long id);
}
Run Code Online (Sandbox Code Playgroud)
...并添加相应的实现:
public SomethingRepositoryImpl extends SimpleJpaRepository<Something, Long>
implements SomethingRepositoryCustom {
public SomethingRepositoryImpl(<Something> domainClass, EntityManager em) {
super(domainClass, em);
this.entityManager = em;
}
@Override
public Something findOne(Long id) {
System.out.println("custom find one");
// do whatever I want and then fetch the object
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
现在,如果我启动应用程序,我会收到以下错误:
... org.springframework.beans.BeanInstantiationException:无法实例[com.dummy.repositories.SomethingRepositoryImpl]:没有发现默认的构造函数; 嵌套的例外是java.lang.NoSuchMethodException:com.dummy.repositories.SomethingRepositoryImpl()...
问题: 如何解决BeanInstantiationException?我假设我需要声明一个存储库工厂bean,但我不知道如何覆盖Spring …