我使用Spring Data Rest,我不明白为什么我的RepositoryRestController不能工作。它的代码是:
@RepositoryRestController
public class Cntrl {
@Autowired
private UserDao userDao;
@RequestMapping(name = "/users/{id}/nameOne",method =
RequestMethod.GET)
@ResponseBody
public PersistentEntityResource setNameOne(@PathVariable("id") Long id, PersistentEntityResourceAssembler persistentEntityResourceAssembler){
User user = userDao.findById(id).orElseThrow(()->{
throw new ServerException("Wrong id");
});
user.setLogin("One");
userDao.save(user);
return persistentEntityResourceAssembler.toFullResource(user);
}
}和Spring Boot启动类:
@SpringBootApplication
@EnableWebMvc
@EnableScheduling
@EnableJpaRepositories
@EnableSpringDataWebSupport
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}当我转到基本路径(localhost:8080/api)时,一切都很好,但是当将GET发送到localhost:8080/api/users/ 1 /nameOne我得到空响应时,我没有其他控制器,并且我有id为1的用户,那么为什么它不工作呢?
发布于 2019-04-22 16:50:29
它不起作用,因为您正在使用的URL结构在Spring Data Rest上下文中已经有了含义。
在RepositoryPropertyReferenceController.followPropertyReference方法中处理/{repository}/{id}/{column} URL。
/api/users/1/nameOne 意思是:获取 id 为 1 的用户的 nameOne 列。重要的一点是:该列应该引用另一个 @Entity。这意味着如果您有一个名为“surname”的String列并且您点击 URL /api/users/1/name 您将得到 404,因为该列没有引用另一个实体。如果您有一个名为 school 的列引用了 School 实体,并且您点击了 URL /api/users/1/school,您将获得该用户的引用学校实体。如果用户没有学校,那么您将再次获得 404。
此外,如果您给出的URL没有与Spring Data Rest冲突,那么@RepositoryRestController也可以用于@RequestMapping。
您可以使用以下示例对其进行测试:
@RepositoryRestController
public class CustomRepositoryRestController {
@RequestMapping(path = "/repositoryRestControllerTest", method = RequestMethod.GET)
@ResponseBody
public String nameOne() {
return "test";
}
}访问http://localhost:8080/repositoryRestControllerTest
我希望这个解释能为你澄清一些事情。
发布于 2019-04-14 20:48:28
如果localhost:8080/api是您的根上下文,那么localhost:8080/api/users/1/nameOne应该是您用于用户获取的url。
https://stackoverflow.com/questions/55675402
复制相似问题