小编典典

具有@PathVariable的Spring MVC带注释的控制器接口

spring-boot

是否有任何理由不将Controller映射为接口?

在我看到的所有示例和问题中,周围的控制器都是具体的类。是否有一个原因?我想将请求映射与实现分开。但是,当我尝试@PathVariable在我的具体课程中获取a
作为参数时,我碰壁了。

我的Controller界面如下所示:

@Controller
@RequestMapping("/services/goal/")
public interface GoalService {

    @RequestMapping("options/")
    @ResponseBody
    Map<String, Long> getGoals();

    @RequestMapping(value = "{id}/", method = RequestMethod.DELETE)
    @ResponseBody
    void removeGoal(@PathVariable String id);

}

和实现类:

@Component
public class GoalServiceImpl implements GoalService {

    /* init code */

    public Map<String, Long> getGoals() {
        /* method code */
        return map;
    }

    public void removeGoal(String id) {
        Goal goal = goalDao.findByPrimaryKey(Long.parseLong(id));
        goalDao.remove(goal);
    }

}

getGoals()方法效果很好;在removeGoal(String id)抛出一个异常

ExceptionHandlerExceptionResolver - Resolving exception from handler [public void
    todo.webapp.controllers.services.GoalServiceImpl.removeGoal(java.lang.String)]: 
    org.springframework.web.bind.MissingServletRequestParameterException: Required 
    String parameter 'id' is not present

如果我将@PathVariable注释添加到具体类中,那么一切都会按预期工作,但是为什么我必须在具体类中重新声明呢?它不应该由带有@Controller注释的东西处理吗?


阅读 350

收藏
2020-05-30

共1个答案

小编典典

显然,当请求模式通过@RequestMapping注释映射到方法时,它就会映射到具体的方法实现。因此,与声明匹配的请求将GoalServiceImpl.removeGoal()直接调用,而不是最初声明@RequestMappingie
的方法GoalService.removeGoal()

由于接口,接口方法或 接口方法参数 上的注释不会延续到实现中,因此@PathVariable除非实现类明确声明,否则Spring
MVC无法将其识别为。没有它,@PathVariable将不会执行任何针对参数的AOP建议。

2020-05-30