1. 程式人生 > 程式設計 >springboot開發擴充套件springmvc實現解析

springboot開發擴充套件springmvc實現解析

這篇文章主要介紹了springboot開發擴充套件springmvc實現解析,文中通過示例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下

可以在Java定義自己配置的springmvc:

springboot開發擴充套件springmvc實現解析

MyMvcConfig.java

package com.gong.springbootcurd.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

//@EnableWebMvc 接管springmvc
@Configuration
public class MyMvcConfig implements WebMvcConfigurer{
  @Override
  public void addViewControllers(ViewControllerRegistry registry) {
    //瀏覽器傳送gong請求會跳轉到/templates/success.html頁面
    registry.addViewController("gong").setViewName("success");
  }
  //所有的WebMvcConfigurer會一起起作用
  //將元件註冊到容器中
  @Bean
  public WebMvcConfigurer webMvcConfigurer() {
    WebMvcConfigurer webMvcConfigurer = new WebMvcConfigurer(){
      public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/index.html").setViewName("index");
      }
    };
    return webMvcConfigurer;
  }

}

關鍵有三點:

(1)實現WebMvcConfigurer。

(2)用Configuration標識配置類。

(3)如果是public WebMvcConfigurer webMvcConfigurer() {...},則需要用@Bean標識。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。