idea運行javaweb項目,@EnableWebMvc啟動springmvc特性

 2023-10-18 阅读 26 评论 0

摘要:使用 @EnableWebMvc @SpringBootApplication public class Application {public static void main(String[] args) {log.debug("access {}","main");SpringApplication.run(Application.class, args);} } WebMvcConfigurerAdapter 實現類,配置

使用

@EnableWebMvc
@SpringBootApplication
public class Application  {public static void main(String[] args) {log.debug("access {}","main");SpringApplication.run(Application.class, args);}
}

WebMvcConfigurerAdapter 實現類,配置跨域,添加靜態頁面等功能

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {@AutowiredRedisData redisData;@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");}@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**").allowedOrigins("*").allowCredentials(true).allowedMethods("GET", "POST", "DELETE", "PUT").maxAge(3600);}}

原理

@EnableWebMvc注解注入了DelegatingWebMvcConfiguration的bean

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
@Import({DelegatingWebMvcConfiguration.class})
public @interface EnableWebMvc {
}

啟動加載所有WebMvcConfigurer實例

@Configuration
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {private final WebMvcConfigurerComposite configurers = new WebMvcConfigurerComposite();public DelegatingWebMvcConfiguration() {}@Autowired(required = false)public void setConfigurers(List<WebMvcConfigurer> configurers) {if(!CollectionUtils.isEmpty(configurers)) {this.configurers.addWebMvcConfigurers(configurers);}}
...
}

WebMvcConfigurerComposite 使用組合模式,是樹枝節點


class WebMvcConfigurerComposite implements WebMvcConfigurer {private final List<WebMvcConfigurer> delegates = new ArrayList();WebMvcConfigurerComposite() {}public void addWebMvcConfigurers(List<WebMvcConfigurer> configurers) {if(!CollectionUtils.isEmpty(configurers)) {this.delegates.addAll(configurers);}}

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/5/148914.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息