Springboot自定義mvc元件如何實現
阿新 • • 發佈:2020-11-19
如果你想實現一些定製化功能,只需要寫這個元件,然後將它交給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; } } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。