【问题标题】:org.springframework.beans.factory.BeanCreationException problemorg.springframework.beans.factory.BeanCreationException 问题
【发布时间】:2020-06-16 08:27:55
【问题描述】:

我正在学习 Spring Boot,我正在创建一个从 JSON 获取数据并将它们放入数据库的项目。在尝试创建 GET 方法时,我遇到了这个异常:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'userController' method 

这是我的控制器。如果有人可以提供帮助,我会很高兴.. 谢谢!

@Autowired
private UserService userService;

@GetMapping("/data")
public List<User> getUsers(){

    List<User> usersFinal = userService.getUsers();

    return usersFinal;
}



public String save50User(User user) {
    List<User> usersFinal = userService.getUsers();
    for(int i = 0;i<50;i++) {
        userService.saveUser(usersFinal.get(i));
    }

    return " the first 50 users saved";
}


@GetMapping("/user/{title}")
public List<User> showByTitle(@PathVariable String title) {
    List<User> s = userService.showByTitleLike(title);
    return s;
}


@GetMapping("/user/{id}")
public List<User> showByUserId(@PathVariable Integer id) {
    List<User> s =  userService.showByUserId(id);
    return s;
}


@GetMapping("/user/{id}")
public User showById(@PathVariable int id) {
    User s = userService.showById(id);
    return s;
}
@GetMapping("/user/{completed}")
public List<User> showCompletedTrue(@PathVariable boolean bool) {
    List<User> s = userService.showByCompleted(bool);
    return s;
}

【问题讨论】:

  • 这个@GetMapping("/user/{id}") 映射存在两次。那是行不通的。
  • @M.Deinum 是的,我明白了!非常感谢

标签: java spring-boot hibernate spring-mvc


【解决方案1】:

抱歉,您所有的 Get Endpoints 都是模棱两可的,都具有相同的模式,不会使它们不同

意思

@GetMapping("/user/{title}")
@GetMapping("/user/{id}")
@GetMapping("/user/{completed}")

如果你调用/user/xyz,它将无法识别需要调用哪个端点以及需要执行哪些代码,因为xyz可以title、id或completed强>

因此,为了使其与众不同,您应该更改 url 模式,例如

@GetMapping("/user/title/{title}")
@GetMapping("/user/id/{id}")
@GetMapping("/user/completed/{completed}")

这将使端点不同,并执行您预期的业务逻辑

【讨论】:

  • 非常感谢!它正在工作..这是我第一个使用带有参数的 @Query 的应用程序,这就是我无法解决这个问题的原因
猜你喜欢
  • 2011-10-07
  • 1970-01-01
  • 2017-01-07
  • 2016-03-03
  • 1970-01-01
  • 2018-05-06
  • 2012-11-18
  • 1970-01-01
  • 2013-12-15
相关资源
最近更新 更多