1. 程式人生 > >Spring MVC之基於java config無xml配置的web應用構建

Spring MVC之基於java config無xml配置的web應用構建

開發十年,就只剩下這套架構體系了! >>>   

更多spring相關博文參考: http://spring.hhui.top

前一篇博文講了SpringMVC+web.xml的方式建立web應用,用過SpringBoot的童鞋都知道,早就沒有xml什麼事情了,其實Spring 3+, Servlet 3+的版本,就已經支援java config,不用再寫xml;本篇將介紹下,如何利用java config取代xml配置

本篇博文,建議和上一篇對比看,貼出上一篇地址

<!-- more -->

I. Web構建

1. 專案依賴

對於依賴這一塊,和前面一樣,不同的在於java config 取代 xml

<artifactId>200-mvc-annotation</artifactId>
<packaging>war</packaging>

<properties>
    <spring.version>5.1.5.RELEASE</spring.version>
</properties>

<dependencies>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.eclipse.jetty.aggregate</groupId>
        <artifactId>jetty-all</artifactId>
        <version>9.2.19.v20160908</version>
    </dependency>
</dependencies>

<build>
    <finalName>web-mvc</finalName>
    <plugins>
        <plugin>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-maven-plugin</artifactId>
            <version>9.4.12.RC2</version>
            <configuration>
                <httpConnector>
                    <port>8080</port>
                </httpConnector>
            </configuration>
        </plugin>
    </plugins>
</build>

細心的童鞋會看到,依賴中多了一個jetty-all,後面測試篇幅會說到用法

2. 專案結構

第二節依然放上專案結構,在這裡把xml的結構也截進來了,對於我們的示例demo而言,最大的區別就是沒有了webapp,更沒有webapp下面的幾個xml配置檔案

專案結構

3. 配置設定

現在沒有了配置檔案,我們的配置還是得有,不然web容器(如tomcat)怎麼找到DispatchServlet呢

a. DispatchServlet 宣告

同樣我們需要乾的第一件事情及時宣告DispatchServlet,並設定它的應用上下文;可以怎麼用呢?從官方找到教程

{% blockquote @SpringWebMvc教程

https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-servlet %}

The DispatcherServlet, as any Servlet, needs to be declared and mapped according to the Servlet specification by using Java configuration or in web.xml. In turn, the DispatcherServlet uses Spring configuration to discover the delegate components it needs for request mapping, view resolution, exception handling

{% endblockquote %}

上面的解釋,就是說下面的程式碼和web.xml的效果是一樣一樣的

public class MyWebApplicationInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletCxt) {
        // Load Spring web application configuration
        AnnotationConfigWebApplicationContext ac = new AnnotationConfigWebApplicationContext();
        ac.register(AppConfig.class);
        ac.refresh();

        // Create and register the DispatcherServlet
        DispatcherServlet servlet = new DispatcherServlet(ac);
        ServletRegistration.Dynamic registration = servletCxt.addServlet("mvc-dispatcher", servlet);
        registration.setLoadOnStartup(1);
        registration.addMapping("/*");
    }
}

當然直接實現介面的方式有點粗暴,但是好理解,上面的程式碼和我們前面的web.xml效果一樣,建立了一個DispatchServlet, 並且綁定了url命中規則;設定了應用上下文AnnotationConfigWebApplicationContext

這個上下文,和我們前面的配置檔案mvc-dispatcher-servlet有點像了;如果有興趣看到專案原始碼的同學,會發現用的不是上面這個方式,而是及基礎介面AbstractDispatcherServletInitializer

public class MyWebApplicationInitializer extends AbstractDispatcherServletInitializer {
    @Override
    protected WebApplicationContext createRootApplicationContext() {
        return null;
    }

    @Override
    protected WebApplicationContext createServletApplicationContext() {
        AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
        //        applicationContext.setConfigLocation("com.git.hui.spring");
        applicationContext.register(RootConfig.class);
        applicationContext.register(WebConfig.class);
        return applicationContext;
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/*"};
    }
    
    @Override
    protected Filter[] getServletFilters() {
        return new Filter[]{new HiddenHttpMethodFilter(), new CharacterEncodingFilter()};
    }
}

看到上面這段程式碼,這個感覺就和xml的方式更像了,比如Servlet應用上下文和根應用上下文

說明

上面程式碼中增加的Filter先無視,後續會有專文講什麼是Filter以及Filter可以怎麼用

b. java config

前面定義了DispatchServlet,接下來對比web.xml就是需要配置掃描並註冊bean了,本文基於JavaConfig的方式,則主要是藉助 @Configuration 註解來宣告配置類(這個可以等同於一個xml檔案)

前面的程式碼也可以看到,上下文中註冊了兩個Config類

RootConfig定義如下,注意下註解@ComponentScan,這個等同於<context:component-sca/>,指定了掃描並註冊啟用的bean的包路徑

@Configuration
@ComponentScan(value = "com.git.hui.spring")
public class RootConfig {
}

另外一個WebConfig的作用則主要在於開啟WebMVC

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
}

4. 例項程式碼

例項和上一篇一樣,一個普通的Server Bean和一個Controller

@Component
public class PrintServer {
    public void print() {
        System.out.println(System.currentTimeMillis());
    }
}

一個提供rest服務的HelloRest

@RestController
public class HelloRest {
    @Autowired
    private PrintServer printServer;

    @GetMapping(path = "hello", produces="text/html;charset=UTF-8")
    public String sayHello(HttpServletRequest request) {
        printServer.print();
        return "hello, " + request.getParameter("name");
    }


    @GetMapping({"/", ""})
    public String index() {
        return UUID.randomUUID().toString();
    }
}

5. 測試

測試依然可以和前面一樣,使用jetty來啟動,此外,介紹另外一種測試方式,也是jetty,但是不同的是我們直接寫main方法來啟動服務

public class SpringApplication {

    public static void main(String[] args) throws Exception {
        Server server = new Server(8080);
        ServletContextHandler handler = new ServletContextHandler();

        // 伺服器根目錄,類似於tomcat部署的專案。 完整的訪問路徑為ip:port/contextPath/realRequestMapping
        //ip:port/專案路徑/api請求路徑
        handler.setContextPath("/");

        AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
        applicationContext.register(WebConfig.class);
        applicationContext.register(RootConfig.class);

        //相當於web.xml中配置的ContextLoaderListener
        handler.addEventListener(new ContextLoaderListener(applicationContext));

        //springmvc攔截規則 相當於web.xml中配置的DispatcherServlet
        handler.addServlet(new ServletHolder(new DispatcherServlet(applicationContext)), "/*");

        server.setHandler(handler);
        server.start();
        server.join();
    }
}

測試示意圖如下

測試示意圖

6. 小結

簡單對比下xml的方式,會發現java config方式會清爽很多,不需要多個xml配置檔案,維持幾個配置類,加幾個註解即可;當然再後面的SpringBoot就更簡單了,幾個註解了事,連上面的兩個Config檔案, ServletConfig都可以省略掉

另外一個需要注意的點就是java config的執行方式,在servlet3之後才支援的,也就是說如果用比較老的jetty是起不來的(或者無法正常訪問web服務)

II. 其他

- 系列博文

web系列:

mvc應用搭建篇:

0. 專案

1. 一灰灰Blog

一灰灰的個人部落格,記錄所有學習和工作中的博文,歡迎大家前去逛逛

2. 宣告

盡信書則不如,以上內容,純屬一家之言,因個人能力有限,難免有疏漏和錯誤之處,如發現bug或者有更好的建議,歡迎批評指正,不吝感激

3. 掃描關注

一灰灰blog

QrCode

知識星球

相關推薦

Spring MVC基於java configxml配置web應用構建

開發十年,就只剩下這套架構體系了! >>>   

Spring MVC基於xml配置web應用構建

開發十年,就只剩下這套架構體系了! >>>   

Spring(八)基於Java配置

onf 需要 rgs ava poi .com class 解釋 mes 基於 Java 的配置 到目前為止,你已經看到如何使用 XML 配置文件來配置 Spring bean。如果你熟悉使用 XML 配置,那麽我會說,不需要再學習如何進行基於 Java 的配置是,因為你要

Maven構建一個多模組的Spring Boot + Spring MVC專案,完全基於java config

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/

Spring MVC的WebMvcConfigurerAdapter用法收集(零配置XML配置

clas security net turn 信息 xxx jsonview frame ppi 原理先不了解,只記錄常用方法 用法: @EnableWebMvc 開啟MVC配置,相當於 <?xml version="1.0" encoding="UTF-

SSM框架專案搭建系列(六)—Spring AOP基於XML的宣告式AspectJ

AOP通過“橫切”技術,剖解開封裝的物件內部,並將那些影響了多個類的公共行為封裝到一個可重用模組,將其命名為Aspect,即切面。 切面就是將那些與業務無關(例如:許可權認證、日誌、事務處理),確為業務模組所共同呼叫的邏輯或責任封裝起來,便於減少系統的重複程式

實現spring mvcjava config 載入不同配置檔案

需要配置一個spring 啟動時的事件監聽器. SpringRootAppInitListener.java 配置類 /** * spring 根容器啟動時的監聽事件 * * @return Application

Spring入門(基於Java的容器註解@Scope和基於泛型的自動裝配)

@Scope 在使用@Bean的時候,預設@Bean定義出來的註解是單例的,那麼有什麼方式可以指定它的範圍呢,我們使用@Scope。Bean的作用域包括singleton、prototype、request、session、global session。 @

如何搭建一個基於Java Config配置的SSM框架(配置檔案)

基於Java形式的專案配置,相比於基於配置檔案的形式更直接,更簡潔,更簡單。使用配置檔案,比如xml,json,properties等形式,都是用程式碼去解析配置檔案內的資訊,然後根據其資訊設定相應配置類的屬性。而Java形式的配置是跳過配置檔案,直接將配置資訊

Spring AOP---基於ProxyFactory的類編碼方式和XML配置方式實現AOP

前一篇文章Spring AOP之—基於JDK動態代理和CGLib動態代理的AOP實現 介紹了AOP的底層實現,基於JDK動態代理和CGLib動態代理。手工編碼的方式很繁瑣,本文介紹通過ProxyFactory和配置的方式實現AOP,方便快捷。 一、Sp

Spring入門(基於Java的容器註解@ImportResource和@Value)

如何使用@ImportResource和@Value進行資原始檔讀取。 首先看個例子,使用beans來定義一個配置 <beans> <context:annotation-config/> <context:

Spring MVC 傳遞模型數據到視圖中

sage size efi ram fix post head bmi 傳遞 類似於 JSP-Servlet 中的 req.setAttribute 、 req.getSession().setAttribute ... --> 最後在 JSP 用 EL 表達式取

Spring mvc源碼 handlerMapping和handlerAdapter分析

執行方法 work 默認 生命 以及 nco refresh 實現 初始化  Spring mvc之源碼 handlerMapping和handlerAdapter分析 本篇並不是具體分析Spring mvc,所以好多細節都是一筆帶過,主要是帶大家梳理一下整個Spring

Appium移動自動化測試基於java的iOS環境搭建

res .sh 變更 order edev curl 軟件包 comm 簡單的 本文僅供參考,同時感謝幫助我搭建環境的同事 操作系統的名稱:Mac OS X操作系統的版本:10.12.6 接下來我們開始踏上搭建Appium+java+ios之路,本文只說個大概,畢竟本機已經

[轉]Spring MVC @PathVariable @CookieValue@RequestParam @RequestBody @RequestHeader@SessionAttributes, @ModelAttribute

tex ice some 不同 配置 this -type pro tro 原文鏈接 http://blog.csdn.net/kobejayandy/article/details/12690161 引言: 接上一篇文章,對@RequestMapping進行地

Spring mvcRestful API

clas 處的 ati code ans 指定 reat get 不能 Spring mvc之Restful API 這是一個路徑,http://127.0.0.1:8080/OperationAPI/v0.1/pins/3是API的具體網址。在RESTful架構中,每個網

Spring(七)基於註解配置

關於 int ESS schema 控制 div except strong ont 基於註解的配置 從 Spring 2.5 開始就可以使用註解來配置依賴註入。而不是采用 XML 來描述一個 bean 連線,你可以使用相關類,方法或字段聲明的註解,將 bean 配置移動到

Spring MVC@RequestMapping 詳解 Spring MVC@RequestMapping 詳解

轉自原文 Spring MVC之@RequestMapping 詳解 引言: 前段時間專案中用到了REST風格來開發程式,但是當用POST、PUT模式提交資料時,發現伺服器端接受不到提交的資料(伺服器端引數繫結沒有加 任何註解),查看了提交方式為application/json, 而且伺服器端通過requ

Java Spring MVC專案搭建(二)——專案配置

文章轉載自:https://www.cnblogs.com/eczhou/p/6287876.html 1、站點配置檔案web.xml 每一個Spring MVC 專案都必須有一個站點配置檔案web.xml,他的主要功能嗎....有一位大哥已經整理的很好,我借來了,大家看看: 引用部落格

Spring MVCMultipartResolver

MultipartResolver是spring提供的檔案上傳解析器的介面,該介面有兩個實現類:StandardServletMultipartResolver、CommonsMultipartResolver,MultipartResolver#isMultipart是判斷是否檔案上傳