1. 程式人生 > 程式設計 >SpringMVC註解版:讀取核心配置類

SpringMVC註解版:讀取核心配置類

有的時候真心不喜歡這個世界!!!

第一步:Servlet容器的初始化

按照之前傳統的方式來配置SpringMVC需要在web.xml中配置DispatcherServlet,但是在Servlet3規範和Spring3.1之後新增了一種方式,那就是java和註解的方式進行配置,今天我們以Spring的最新版本5.2.1.RELEASE來進行一下配置,一起來看一下吧!

mvc-context-hierarchy.png

在Web MVC框架中,每個DispatcherServlet都有自己的WebApplicationContext,它繼承了在根WebApplicationContext中已經定義的所有bean。 根WebApplicationContext應該包含應在其他上下文和Servlet例項之間共享的所有基礎結構Bean。 這些繼承的bean可以在servlet特定的作用域中被覆蓋,並且您可以在給定Servlet例項本地定義新的特定於作用域的bean。
複製程式碼

下面的配置來自域官方檔案:

取消web.xml改用java來配置首先需要有一個入口,下面展示了這個入口,即先建立一個初始化的類GolfingWebAppInitializer ,GolfingWebAppInitializer 類繼承了一個名為AbstractAnnotationConfigDispatcherServletInitializer的抽象類,同樣這個抽象類實現了org.springframework.web.WebApplicationInitializer介面。
複製程式碼
public class GolfingWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer
{ @Override protected Class<?>[] getRootConfigClasses() { // GolfingAppConfig defines beans that would be in root-context.xml return new Class[] { GolfingAppConfig.class };//Spring框架的核心配置檔案 } @Override protected Class<?>[] getServletConfigClasses() { // GolfingWebConfig defines beans that would be in golfing-servlet.xml
return new Class[] { GolfingWebConfig.class };//Spring MVC框架的核心配置檔案 } @Override protected String[] getServletMappings() { return new String[] { "/" }; } } 複製程式碼
  • 繼承AbstractAnnotationConfigDispatcherServletInitializer需要實現三個方法,其中getServletMappings()會返回一個路徑陣列,將一個或多個路徑對映到DispatcherServlet上,本例中它對映的是“/”,表示DispatcherServlet會處理所有的請求。

  • getServletConfigClasses()方法要返回一個帶有@Configuration註解的類,這個類將會用來定義DispatcherServlet應用上下文。

  • getRootConfigClasses()方法要返回一個帶有@Configuration註解的類,這個類將會用來配置原來xml中ContextLoaderListener所建立的應用上下文。

啟動原理:

在Servlet3.0環境中容器會查詢類路徑下的實現了javax.servlet.ServletContainerInitializer介面的類,找到了就會用它來配置Servlet容器。從這個介面的全限定名稱上可以看出它是java標準api的一部分,是在Servlet 3.0以後才新增的。Spring為這個介面提供了一個實現類:

package org.springframework.web;

@HandlesTypes({WebApplicationInitializer.class})
public class SpringServletContainerInitializer implements ServletContainerInitializer {
    public SpringServletContainerInitializer() {}
}
複製程式碼

這個實現類又會把配置任務交給WebApplicationInitializer介面的實現類來完成。我們這裡實現的抽象類AbstractAnnotationConfigDispatcherServletInitializer正是WebApplicationInitializer的一個實現類。而我們的GolfingWebAppInitializer正是AbstractAnnotationConfigDispatcherServletInitializer的一個擴充套件,所以這樣就把配置任務最終交給了我們自定義的這個配置類GolfingWebAppInitializer。


第二步:SpringMVC配置

package com.os;

import com.os.config.SpringMvcConfigurer;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class GolfingWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[0];
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{
            SpringMvcConfigurer.class/*這個就是SpringMVC的核心配置檔案,相當於之前配置果的xml*/
        };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };//對映的路徑
    }
}
複製程式碼

SpringMvcConfigurer

package com.os.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@ComponentScan(basePackages = "com.os.**.web")
public class SpringMvcConfigurer implements WebMvcConfigurer {

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        InternalResourceViewResolver jspViewResolver = new InternalResourceViewResolver();
        jspViewResolver.setPrefix("/WEB-INF/jsp/");
        jspViewResolver.setSuffix((".jsp"));

        registry.viewResolver(jspViewResolver);
    }
}
複製程式碼

WebMvcConfigurer提供了回撥方法來供我們自定義SpringMVC的預設配置。如果是使用@EnableWebMvc註解的話表示啟用WebMvcConfigurationSupport類的預設配置。我們並沒有使用@EnableWebMvc註解而是實現了WebMvcConfigurer,這樣做是為了擴充套件。

第三步:編寫Controller

package com.os.web;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/user")
public class IndexController {
    @GetMapping("/add")
    public String add(){
        return "add";
    }
}
複製程式碼

Snap1.jpg

基本上就搞定了!釋出一下專案就行了,這裡沒有使用Tomcat外掛的形式進行釋出,還是使用原始的釋出方式,這裡就不過多說明和配置了,這些東西還是比較簡單的!上述配置和載入SpringMVC的核心配置檔案的方式是我們推薦的方式,但是還有一種可以讀取前端控制器的方式,這裡簡單的記錄一下!

附錄

package com.hanpang.config;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

public class HelloWorldInitializer implements WebApplicationInitializer {

	@Override
	public void onStartup( ServletContext application ) throws ServletException {
		System.out.println("開始載入容器");
		AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
		ctx.register(SpringMvcConfiguration.class);//核心類
		ctx.setServletContext(application);

		ServletRegistration.Dynamic servlet = application.addServlet("dispatcher",new DispatcherServlet(ctx));

		servlet.setLoadOnStartup(2);
		servlet.addMapping("/");

	}

}
複製程式碼