1. 程式人生 > >Spring、SpringMVC版本及配置

Spring、SpringMVC版本及配置

  一、Spring版本

  Spring的最新版本是Spring 5.x,Spring 4.x的最後版本是Spring 4.4.x,會維護到2020年(Spring的GitHub主頁對此有說明)。

  

 

  二、SpringMVC

  SpringMVC可以說是,應用了Spring的各種特性的一個MVC專案,它的核心Servlet是DispatcherServlet。

 

  三、配置

  各種Java框架一般都需要在web.xml中進行相關配置,一般都涉及到Listener、Filter、Servlet。

  3.1 web.xml中配置

  在Spring 3.1版本之前,在web.xml中配置DispatcherServlet是唯一的方式(同時宣告對映):

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>

    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
/WEB-INF/spring/dispatcher-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>

**註釋:load-on-startup

 is an integer value that specifies the order for multiple servlets to be loaded. So if you need to declare more than one servlet you can define in which order they will be initialized. Servlets marked with lower integers are loaded before servlets marked with higher integers.

 

  3.2 web.xml和Java類中均可配置,即可混合配置

  接下來,隨著Servlet API 3.0的應用,web.xml中的配置不是必須的了,我們可以在Java類中配置DispatcherServlet:

public class MyWebAppInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext container) {
        XmlWebApplicationContext context = new XmlWebApplicationContext();
        context.setConfigLocation("/WEB-INF/spring/dispatcher-config.xml");
 
        ServletRegistration.Dynamic dispatcher = container
          .addServlet("dispatcher", new DispatcherServlet(context));
 
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");
    }
}

  這裡的Java配置類取得的最終效果與3.1節中的相同。

  但是我們仍然使用了一個XML檔案:dispatcher-config.xml

 

  3.3 100%的Java配置

  通過對3.2節中的Java配置類進行重構,我們無需再使用XML檔案來配置Dispatcher:

public class MyWebAppInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext container) {
        AnnotationConfigWebApplicationContext context
          = new AnnotationConfigWebApplicationContext();

     //context.register(AppConfig.class); context.setConfigLocation(
"com.example.app.config"); container.addListener(new ContextLoaderListener(context)); ServletRegistration.Dynamic dispatcher = container .addServlet("dispatcher", new DispatcherServlet(context)); dispatcher.setLoadOnStartup(1); dispatcher.addMapping("/"); } }

**註釋:

  The first thing we will need to do is create the application context for the servlet.

  This time we will use an annotation based context so that we can use Java and annotations for configuration and remove the need for XML files like dispatcher-config.xml.

 

  3.4 總結

  Spring 3.2及其以上的版本,均可以採用以上三種方式進行配置。

  官方推薦純Java類來配置,更加簡潔和靈活。但是有時候必須XML檔案也是無法避免的

 

四、SpringBoot化繁為簡

  這些配置很繁瑣,SpringBoot就是達到一鍵生成的效果!