Use WebMvcConfigurerAdapter to configure springmvc related content

foreword

Recently, I took over a project. To develop an iterative version, it is necessary to look at the original structure of the project for a long time.
First of all, I looked for the configuration file related to spring, and found that there is no such thing, which is strange. How is it configured? Then I thought that it might be configured with a java class. Sure enough, I found a related class that inherits WebMvcConfigurerAdapter to achieve the purpose of configuration.

configuration code

Let's talk about a few important configurations. The others are similar, and they are the same as the xml configuration, but they are written differently.
Code first:

@Configuration
@EnableWebMvc
@EnableCaching
@Import({ 
    CacheConfiguration.class,
    RedisConfiguration.class,
    MemcachedConfiguration.class
})
@ComponentScan(basePackages = { 
        "com.test.demo.app.converter"
        ,"com.test.demo.app.api"
        ,"com.test.demo.app.aop"
        ,"com.test.demo.app.mvc"
        ,"com.test.demo.app.config" })
@ImportResource({ "classpath:/dubbo-consumer.xml"
    })
public class MvcConfiguration extends WebMvcConfigurerAdapter {

    private Logger logger = LoggerFactory.getLogger(MvcConfiguration.class);

    @Bean
    //@Lazy
    public SpringContextHolder springContextHolder() {
        return new SpringContextHolder();
    }

    @Bean
    public FreeMarkerConfigurer freemarkerConfig(){
        FreeMarkerConfigurer config = new FreeMarkerConfigurer();
        config.setTemplateLoaderPath("/WEB-INF/template/");
        config.setDefaultEncoding("utf-8");
        Properties properties = new Properties();
        properties.setProperty("locale", "zh_CN");
        properties.setProperty("datetime_format", "yyyy-MM-dd HH:mm:ss");
        properties.setProperty("date_format", "yyyy-MM-dd");
        properties.setProperty("number_format", "#.##");
        properties.setProperty("template_exception_handler", "rethrow");
        properties.setProperty("object_wrapper", "beans");
        config.setFreemarkerSettings(properties);
        return config;
    }

    @Bean
    public FreeMarkerViewResolver viewResolver(){
        FreeMarkerViewResolver viewResover = new FreeMarkerViewResolver();
        viewResover.setCache(false);
        viewResover.setPrefix("");
        viewResover.setSuffix(".ftl");
        viewResover.setContentType("text/html;charset=UTF-8");
        viewResover.setRequestContextAttribute("request");
        viewResover.setExposeRequestAttributes(true);
        viewResover.setExposeSessionAttributes(true);
        viewResover.setExposeSpringMacroHelpers(true);
        return viewResover;
    }



    @Bean
    public static PropertyPlaceholderConfigurer properties() {
        PropertyPlaceholderConfigurer propertyPlaceholder = new PropertyPlaceholderConfigurer();
        ClassPathResource[] resources = new ClassPathResource[] { new ClassPathResource("app.properties") };
        propertyPlaceholder.setLocations(resources);
        propertyPlaceholder.setIgnoreUnresolvablePlaceholders(true);
        return propertyPlaceholder;
    }

    @Bean
    public CacheManager cacheManager(EhCacheManagerFactoryBean factory) {
        return new EhCacheCacheManager(factory.getObject());
    }

    @Bean
    public EhCacheManagerFactoryBean ehCacheCacheManager() {
        EhCacheManagerFactoryBean cmfb = new EhCacheManagerFactoryBean();
        cmfb.setConfigLocation(new ClassPathResource("ehcache.xml"));
        cmfb.setShared(true);
        return cmfb;
    }

    @Bean(name="localeResolver")
    public CookieLocaleResolver cookieLocaleResolver(){
        CookieLocaleResolver localResovler = new CookieLocaleResolver();
        localResovler.setDefaultLocale(Locale.CHINA);
        localResovler.setCookieName("locale");
        return localResovler;
    }


    /**
     * multipart上传配置
     * @return
     */
    @Bean
    public CommonsMultipartResolver multipartResolver(){
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
        multipartResolver.setMaxUploadSize(50 * 1024 * 1024l);  //50m
        return multipartResolver;
    }

    /**
     * api转发拦截器
     */
    @Bean
    public ApiForwardInterceptor apiForwardInterceptor() {
        logger.info("initializing ApiForwardInterceptor ...");
        return new ApiForwardInterceptor();
    }

    /**
     * web转发拦截器
     */
//  @Bean
//  public WebInterceptor webInterceptor(){
//      logger.info("initializing WebInterceptor ...");
//      return new WebInterceptor();
//  }

    /**
     * 拦截器配置
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(apiForwardInterceptor()).addPathPatterns("/test/**");
//      registry.addInterceptor(webInterceptor()).addPathPatterns("/qr/**");
        registry.addInterceptor(localeChangeInterceptor());
        super.addInterceptors(registry);
    }

      @Override  
      public void addResourceHandlers(ResourceHandlerRegistry registry) {  
          registry.addResourceHandler("/resources/**")  
          .addResourceLocations("/resources/");  
      }  

    /**
     * 国际化语言切换拦截器
     * @return
     */
    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {
        logger.info("initializing LocaleChangeInterceptor ...");
        return new LocaleChangeInterceptor();
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        Charset gbk = Charset.forName("GBK");
        Charset utf8 = Charset.forName("UTF-8");

        MyFastJsonHttpMessageConverter jsonConverter = new MyFastJsonHttpMessageConverter();
        jsonConverter.setSupportedMediaTypes(Arrays.asList(
                new MediaType("text", "html", utf8)
                , new MediaType("application", "json"), new MediaType("application", "*+json", gbk)
                , new MediaType("application", "json", utf8), new MediaType("application", "*+json", utf8)
                ));
        jsonConverter.setFeatures(
                SerializerFeature.DisableCircularReferenceDetect, 
                SerializerFeature.WriteMapNullValue, 
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteNullStringAsEmpty, 
                SerializerFeature.WriteNullBooleanAsFalse);
        converters.add(jsonConverter);
        super.configureMessageConverters(converters);
    }
}

Parse

Here is a little explanation of the above configuration:

1. About annotations

@Configuration : Indicates that the class is a configuration class
@EnableWebMvc : Indicates that this class enables the java webmvc configuration, which is <mvc:annotation-driven>consistent with the effect in the xml configuration
@EnableCaching : Indicates that caching is enabled
@Import ({
CacheConfiguration.class,
RedisConfiguration.class,
MemcachedConfiguration.class
})
Import the cache configuration, where multiple caches are imported, which can be added or deleted according to your own needs.
@ComponentScan (basePackages = {
"com.test.demo.app.converter"
, "com.test.demo.app.api"
, "com.test.demo.app.aop"
, "com.test.demo.app .mvc”
,”com.test.demo.app.config” })
automatically scan the package, basePackages specifies the base package
@ImportResource ({ “classpath:/dubbo-consumer.xml”
})
to import the resource file

2. Configure beans

Here are a few commonly used bean configurations
SpringContextHolder : used to hold ApplicationContext, easy to obtain spring beans;
freemarkerConfig : related configuration of freemarker, other templates can also be configured into other templates;
PropertyPlaceholderConfigurer : Load configuration files;
CommonsMultipartResolver : Upload related configuration;
addInterceptors : interceptor configuration, to increase the interceptor money, first configure the corresponding interceptor as a bean;
configureMessageConverters : data conversion bean

Summarize

The general configuration is these, and there are many other configurations that are consistent with xml, which are all the same, and readers can study by themselves.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326369352&siteId=291194637