在这篇文章中,我们将带领您了解是否可以扩展WebMvcConfigurationSupport并使用WebMvcAutoConfiguration?的全貌,同时,我们还将为您介绍有关@EnableWe
在这篇文章中,我们将带领您了解是否可以扩展WebMvcConfigurationSupport并使用WebMvcAutoConfiguration?的全貌,同时,我们还将为您介绍有关@EnableWebMvc,WebMvcConfigurationSupport,WebMvcConfigurer和WebMvcConfigurationAdapter区别、Interceptor,WebMvcConfigurationSupport,Cors 拦截器,全局跨域、Knife4j与WebMvcConfigurationSupport冲突、org.springframework.boot.actuate.autoconfigure.EndpointWebMvcAutoConfiguration的实例源码的知识,以帮助您更好地理解这个主题。
本文目录一览:- 是否可以扩展WebMvcConfigurationSupport并使用WebMvcAutoConfiguration?
- @EnableWebMvc,WebMvcConfigurationSupport,WebMvcConfigurer和WebMvcConfigurationAdapter区别
- Interceptor,WebMvcConfigurationSupport,Cors 拦截器,全局跨域
- Knife4j与WebMvcConfigurationSupport冲突
- org.springframework.boot.actuate.autoconfigure.EndpointWebMvcAutoConfiguration的实例源码
是否可以扩展WebMvcConfigurationSupport并使用WebMvcAutoConfiguration?
我还需要扩展WebMvcConfigurationSupport类,还要修改两件事:
@Configurationpublic class WebConfig extends WebMvcConfigurationSupport { @Override public RequestMappingHandlerMapping requestMappingHandlerMapping() { RequestMappingHandlerMapping handlerMapping = super.requestMappingHandlerMapping(); handlerMapping.setRemoveSemicolonContent(false); handlerMapping.setOrder(1); return handlerMapping; }}
我喜欢从WebMvcAutoConfiguration类中注册的默认值,但是由于该类上的条件注释,当我扩展WebMvcConfigurationSupport类时,它将阻止自动配置的发生。
@Configuration@ConditionalOnWebApplication@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurerAdapter.class })@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)@Order(Ordered.HIGHEST_PRECEDENCE + 10)@AutoConfigureAfter(DispatcherServletAutoConfiguration.class)public class WebMvcAutoConfiguration {...}
是否需要加载WebMvcAutoConfiguration类,而不必本质上复制/粘贴该类中的大多数代码?
或者是否可以从其他地方调用RequestMappingHandlerMapping
setOrder()和setRemoveSemicolonContent(),这样我就可以使用@EnableWebMvc批注并运行自动配置类而不会出现任何问题?
提前致谢!
答案1
小编典典您的分析是正确的(@EnableWebMvc
或直接扩展WebMvcConfigurationSupport
将关闭WebMvcAutoConfiguration
)。我不确定替代方案是什么,因为a)我们需要为autoconfig设置一个“
get-
out”子句,并且b)我不认为Spring喜欢WebMvcConfigurationSupports
在相同的上下文中包含两个。很高兴在github上讨论是否想要尝试找到一种更改它的方法(可能会有一些中间立场)。
@EnableWebMvc,WebMvcConfigurationSupport,WebMvcConfigurer和WebMvcConfigurationAdapter区别
@EnableWebMvc是什么
直接看源码,@EnableWebMvc实际上引入一个DelegatingWebMvcConfiguration。
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
@Import({DelegatingWebMvcConfiguration.class})
public @interface EnableWebMvc {
}
DelegatingWebMvcConfiguration继承了WebMvcConfigurationSupport
@Configuration
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
...
所以@EnableWebMvc=继承DelegatingWebMvcConfiguration=继承WebMvcConfigurationSupport
@EnableWebMvc和@EnableAutoConfiguration的关系
@EnableAutoConfiguration是springboot项目的启动类注解@SpringBootApplication的子元素,主要功能为自动配置。
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
excludeFilters = {@Filter(
type = FilterType.CUSTOM,
classes = {TypeExcludeFilter.class}
), @Filter(
type = FilterType.CUSTOM,
classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication {
...
}
@EnableAutoConfiguration实际是导入了EnableAutoConfigurationImportSelector和Registrar两个类
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import({AutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {
...
}
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import({Registrar.class})
public @interface AutoConfigurationPackage {
}
这两个类的具体原理有些复杂,不太清除,主要内容是通过SpringFactoriesLoader.loadFactoryNames()导入jar下面的配置文件META-INF/spring.factories
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
List<String> configurations = SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader());
Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you are using a custom packaging, make sure that file is correct.");
return configurations;
}
配置文件中的内容如下
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
...
org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration,\
...
其中有WebMvcAutoConfiguration,WebMvcAutoConfiguration源码如下
@Configuration
@ConditionalOnWebApplication(
type = Type.SERVLET
)
@ConditionalOnClass({Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class})
@ConditionalOnMissingBean({WebMvcConfigurationSupport.class})
@AutoConfigureOrder(-2147483638)
@AutoConfigureAfter({DispatcherServletAutoConfiguration.class, ValidationAutoConfiguration.class})
public class WebMvcAutoConfiguration {
...
}
@ConditionalOnMissingBean({WebMvcConfigurationSupport.class})意思是如果存在它修饰的类的bean
,则不需要再创建这个bean。
由此可得出结论:
如果有配置文件继承了DelegatingWebMvcConfiguration,
或者WebMvcConfigurationSupport,或者配置文件有@EnableWebMvc,那么 @EnableAutoConfiguration 中的
WebMvcAutoConfiguration 将不会被自动配置,而是使用WebMvcConfigurationSupport的配置。
@EnableWebMvc,WebMvcConfigurationSupport,WebMvcConfigurer和WebMvcConfigurationAdapter使用
WebMvcConfigurationAdapter已经废弃,最好用implements WebMvcConfigurer代替
@Configuration
public class MyConfig implements WebMvcConfigurer {
}
如果使用继承,WebMvcConfigurationSupport,DelegatingWebMvcConfiguration,或者使用@EnableWebMvc,
需要注意会覆盖application.properties中关于WebMvcAutoConfiguration的设置,需要在自定义配置中实现,如
springboot2.0、spring5.0 拦截器配置WebMvcConfigurerAdapter过时使用WebMvcConfigurationSupport来代替 新坑
示例如下
Configuration
@EnableWebMvc
public class MyConfig implements WebMvcConfigurer {
}
@Configuration
public class MyConfig extends WebMvcConfigurationSupport {
}
@Configuration
public class MyConfig extends DelegatingWebMvcConfiguration {
}
上面代码中需要在类中实现关于WebMvcAutoConfiguration的配置,而不是在application.properties中。
总结
implements WebMvcConfigurer : 不会覆盖@EnableAutoConfiguration关于WebMvcAutoConfiguration的配置
@EnableWebMvc + implements WebMvcConfigurer : 会覆盖@EnableAutoConfiguration关于WebMvcAutoConfiguration的配置
extends WebMvcConfigurationSupport :会覆盖@EnableAutoConfiguration关于WebMvcAutoConfiguration的配置
extends DelegatingWebMvcConfiguration :会覆盖@EnableAutoConfiguration关于WebMvcAutoConfiguration的配置
Interceptor,WebMvcConfigurationSupport,Cors 拦截器,全局跨域
1:实现 HandlerInterceptor 接口
public class LoginInterceptor implements HandlerInterceptor {
static Log logger = LogFactory.getLog(LoginInterceptor.class);
//登录之前的校验
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
logger.debug("登录之前的校验");
//todo 拦截的功能
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
2:实现 WebMvcConfigurationSupport 接口,重写 addInterceptors 方法, Configuration 注解标记为配置类
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport { //WebMvcConfigurerAdapter
//拦截器注册
@Override
public void addInterceptors(InterceptorRegistry registry) {
// registry.addInterceptor(new TestInterceptor()).addPathPatterns("/**"); // /**下的每一个接口都要有"登录"的校验
registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/mes");//mes下的接口都要被拦截
super.addInterceptors(registry);
}
//全局跨域
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") // 允许跨域访问的路径
// .allowedOrigins("http://domain2.com") //允许跨域访问的源
// .allowedMethods("PUT", "DELETE") //允许请求方法
// .allowedHeaders("header1", "header2", "header3") //允许头部设置
// .exposedHeaders("header1", "header2")
// .allowCredentials(false).maxAge(3600); //是否发送cookie,预检间隔时间
;
}
//如果有安全框架,需要在框架中启用CORS;还有一种基于"过滤器"的跨域设置
}
Knife4j与WebMvcConfigurationSupport冲突
@Component
public class AppWebMvcConfigurationSupport extends WebMvcConfigurationSupport {
/**
* Controller 方法参数注入
*
* @param argumentResolvers
*/
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(new HandlerMethodArgumentResolver() {
@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.hasParameterAnnotation(Cache.class);
}
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest,
WebDataBinderFactory binderFactory) throws Exception {
HttpServletRequest request = (HttpServletRequest) webRequest.getNativeRequest();
return JwtUtils.getxxxxFromRequest(request);
}
});
}
}
@Configuration
@EnableSwagger2WebMvc
public class Knife4jConfig {
@Bean
public Docket defaultApi() {
return new Docket(DocumentationType.SWAGGER_2).host("http://localhost:8080").groupName("1.0").select()
.apis(RequestHandlerSelectors.basePackage("top.xxx.local.web")).paths(PathSelectors.any()).build();
}
}
参数注入生效, 但knife4j的页面报404
org.springframework.boot.actuate.autoconfigure.EndpointWebMvcAutoConfiguration的实例源码
@Before public void createContext() { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); this.context.register(JacksonAutoConfiguration.class,HttpMessageConvertersAutoConfiguration.class,EndpointAutoConfiguration.class,EndpointWebMvcAutoConfiguration.class,ManagementServerPropertiesAutoConfiguration.class,PropertyPlaceholderAutoConfiguration.class,JolokiaAutoConfiguration.class,WebMvcAutoConfiguration.class); }
@Before public void createContext() { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); this.context.register(JacksonAutoConfiguration.class,WebMvcAutoConfiguration.class); }
@Before public void createContext() { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); this.context.register(JacksonAutoConfiguration.class,WebMvcAutoConfiguration.class); }
关于是否可以扩展WebMvcConfigurationSupport并使用WebMvcAutoConfiguration?的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于@EnableWebMvc,WebMvcConfigurationSupport,WebMvcConfigurer和WebMvcConfigurationAdapter区别、Interceptor,WebMvcConfigurationSupport,Cors 拦截器,全局跨域、Knife4j与WebMvcConfigurationSupport冲突、org.springframework.boot.actuate.autoconfigure.EndpointWebMvcAutoConfiguration的实例源码的相关知识,请在本站寻找。
本文标签: