Springboot mvc Springboot自定义mvc组件怎样实现

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Springboot mvc Springboot自定义mvc组件怎样实现

Y_wee   2021-03-15 我要评论
想了解Springboot自定义mvc组件怎样实现的相关内容吗,Y_wee在本文为您仔细讲解Springboot mvc的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Springboot,自定义,mvc,组件,下面大家一起来学习吧。

如果你想实现一些定制化功能,只需要写这个组件,然后将它交给springboot管理,springboot会给我们自动装配

以下是spring官方文档解释

由官方文档可知,想要自定义组件,需要实现以下步骤

  • 写一个配置类,加上@Configuration注解
  • 实现WebMvcConfigurer接口
  • 不添加@EnableWebMvc注解

示例:自定义视图解析器

package com.yl.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Locale;

/**
 * mvc配置类
 */
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {

  /**
   * 将自定义视图解析器配置成bean存入spring
   */
  @Bean
  public ViewResolver myViewResovler(){
    return new MyViewResolver();
  }


  /**
   * 自定义视图解析器,实现视图解析器接口
   */
  public static class MyViewResolver implements ViewResolver{

    @Override
    public View resolveViewName(String viewName, Locale locale) throws Exception {
      return null;
    }
  }
}

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们