Spring Boot 2 @EnableWebMvc 註解和@EnableSpringDataWebSupport 註解使用說明

1. @EnableWebMvc使用說明

@EnableWebMvc 只能添加到一個@Configuration配置類上,用於導入Spring Web MVC configuration

可以有多個@Configuration類來實現WebMvcConfigurer,以定製提供的配置。

WebMvcConfigurer 沒有暴露高級設置,如果需要高級設置 需要 刪除@EnableWebMvc並繼承WebMvcConfigurationSupport

  • 說明:
    1. Spring Boot 默認提供Spring MVC 自動配置,不需要使用@EnableWebMvc註解
    2. 如果需要配置MVC(攔截器、格式化、視圖等) 請使用添加@Configuration並實現WebMvcConfigurer接口.不要添加@EnableWebMvc註解 參考文檔
    3. 修改靜態屬性匹配URL (靜態資源將會匹配/resources/開頭的URL)
      spring.mvc.static-path-pattern=/resources/**

2. @EnableSpringDataWebSupport 使用說明

  • 該註解默認注入的Bean
    • org.springframework.data.repository.support.DomainClassConverter
    • org.springframework.web.bind.annotation.PathVariable
    • org.springframework.web.bind.annotation.RequestParam
    • org.springframework.data.web.SortHandlerMethodArgumentResolver
    • org.springframework.data.web.PagedResourcesAssembler
    • org.springframework.data.web.SortHandlerMethodArgumentResolver

2.1 使用情況1


@Controller
@RequestMapping("/users")
class UserController {

  private final UserRepository repository;

  UserController(UserRepository repository) {
    this.repository = repository;
  }

  @RequestMapping
  String showUsers(Model model, Pageable pageable) {

    model.addAttribute("users", repository.findAll(pageable));
    return "users";
  }
}

Controller 方法參數中要使用Pageable參數分頁的話,需要添加@EnableSpringDataWebSupport 註解

2.2 使用情況2

@Controller
@RequestMapping("/users")
class UserController {

  @RequestMapping("/{id}")
  String showUserForm(@PathVariable("id") User user, Model model) {

    model.addAttribute("user", user);
    return "userForm";
  }
}

這種方式也需要@EnableSpringDataWebSupport註解才能支持

問題

1. spring boot 2.x 提示 No primary or default constructor found for interface Pageable 解決辦法

出現這個問題解決辦法

    1. 將@EnableSpringDataWebSupport 添加到啓動類上(如果配置類繼承WebMvcConfigurationSupport則無效)
    1. 如果配置類繼承了WebMvcConfigurationSupport那麼@EnableSpringDataWebSupport註解將失效,需要手動注入PageableHandlerMethodArgumentResolver
@Configuration
public class InterceptorConfig extends WebMvcConfigurationSupport {
    @Override
    protected void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(new PageableHandlerMethodArgumentResolver());
    }
}

也就是說,如果要配置WebMvcConfigurationSupport那麼就不要添加@EnableSpringDataWebSupport,如果要使用@EnableSpringDataWebSupport那麼配置文件就不應該繼承WebMvcConfigurationSupport,可以通過實現WebMvcConfigurer接口來達到同樣目的

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章