1. 程式人生 > >Spring Boot 2 @EnableWebMvc 註解和@EnableSpringDataWebSupport 註解使用說明

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介面來達到同樣目的