1. @EnableWebMvc使用说明
@EnableWebMvc 只能添加到一个@Configuration配置类上,用于导入Spring Web MVC configuration
可以有多个@Configuration类来实现WebMvcConfigurer,以定制提供的配置。
WebMvcConfigurer 没有暴露高级设置,如果需要高级设置 需要 删除@EnableWebMvc并继承WebMvcConfigurationSupport
- 说明:
- Spring Boot 默认提供Spring MVC 自动配置,不需要使用@EnableWebMvc注解
- 如果需要配置MVC(拦截器、格式化、视图等) 请使用添加@Configuration并实现WebMvcConfigurer接口.不要添加@EnableWebMvc注解 参考文档
- 修改静态属性匹配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 解决办法
出现这个问题解决办法
-
- 将@EnableSpringDataWebSupport 添加到启动类上(如果配置类继承WebMvcConfigurationSupport则无效)
-
- 如果配置类继承了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接口来达到同样目的