Spring MVC 的 Java Config ( 非 XML ) 配置方式


索引:

目錄索引

參看代碼 GitHub:

solution/pom.xml

web/pom.xml

web.xml

WebInitializer.java

WebConfig.java

RootConfig.java

一、引入必要類庫

  spring-context

  spring-context-support

  spring-webmvc:引入該包后,maven 會自動解析依賴,引入 spring-web 等包。

  1.solution/pom.xml

  1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  3     <modelVersion>4.0.0</modelVersion>
  4 
  5     <groupId>lm.solution</groupId>
  6     <artifactId>solution</artifactId>
  7     <version>1.0-SNAPSHOT</version>
  8     <modules>
  9         <module>webapi</module>
 10         <module>web</module>
 11         <module>common</module>
 12         <module>service</module>
 13         <module>mapper</module>
 14         <module>pojo</module>
 15         <module>console</module>
 16         <module>webservice</module>
 17     </modules>
 18     <packaging>pom</packaging>
 19 
 20     <name>solution</name>
 21     <url>http://maven.apache.org</url>
 22 
 23     <properties>
 24         <!--編譯字符集-->
 25         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 26         <!-- spring -->
 27         <spring.version>4.3.13.RELEASE</spring.version>
 28         <!-- log4j -->
 29         <slf4j.version>1.7.7</slf4j.version>
 30         <log4j.version>1.2.17</log4j.version>
 31         <!-- jackson -->
 32         <jackson.version>2.9.4</jackson.version>
 33         <!-- junit -->
 34         <junit.version>4.12</junit.version>
 35         <!-- aspectj -->
 36         <aspectj.version>1.8.13</aspectj.version>
 37         <!-- cglib -->
 38         <cglib.version>3.1</cglib.version>
 39         <!-- mybatis -->
 40         <mybatis.version>3.4.5</mybatis.version>
 41         <!-- mybatis-spring -->
 42         <mybatisSpring.version>1.3.1</mybatisSpring.version>
 43         <!--mysql-connector-->
 44         <mysql.version>5.1.34</mysql.version>
 45         <!--druid-->
 46         <druid.version>1.0.5</druid.version>
 47         <!--javax.servlet-->
 48         <javaxServlet.version>3.0.1</javaxServlet.version>
 49         <!--jsp-api-->
 50         <jspApi.version>2.2</jspApi.version>
 51         <!--jstl-->
 52         <jstl.version>1.2</jstl.version>
 53         <!--json-lib-->
 54         <jsonLib.version>2.1</jsonLib.version>
 55         <!--jackson old-->
 56         <jacksonOld.version>1.9.13</jacksonOld.version>
 57         <!--dom4j-->
 58         <dom4j.version>1.6.1</dom4j.version>
 59         <!--ehcache core-->
 60         <ehcacheCore.version>2.6.9</ehcacheCore.version>
 61         <!--ehcache web-->
 62         <ehcacheWeb.version>2.0.4</ehcacheWeb.version>
 63         <!--commons-fileupload-->
 64         <commonsFileupload.version>1.3.1</commonsFileupload.version>
 65         <!--commons-io-->
 66         <commonsIo.version>2.4</commonsIo.version>
 67         <!--commons-codec-->
 68         <commonsCodec.version>1.9</commonsCodec.version>
 69         <!--commons-collections4-->
 70         <commonsCollections4.version>4.0</commonsCollections4.version>
 71         <!--commons-beanutils-->
 72         <commonsBeanutils.version>1.7.0</commonsBeanutils.version>
 73         <!--freemarker-->
 74         <freemarker.version>2.3.19</freemarker.version>
 75         <!-- poi  poi-ooxml -->
 76         <poi.version>3.9</poi.version>
 77         <!--org.apache.httpcomponents-->
 78         <httpcore.version>4.4.8</httpcore.version>
 79         <httpclient.version>4.5.4</httpclient.version>
 80         <!-- jaxws-rt -->
 81         <jaxwsRt.version>2.3.0</jaxwsRt.version>
 82         <!-- jedis -->
 83         <jedis.version>2.9.0</jedis.version>
 84         <!-- rabbitmq -->
 85         <amqpClient.version>5.1.2</amqpClient.version>
 86         <!--fastjson-->
 87         <fastjson.version>1.2.46</fastjson.version>
 88         <!-- jsr250 -->
 89         <jsr250.version>1.0</jsr250.version>
 90     </properties>
 91 
 92     <dependencies>
 93         <!--單元測試依賴 -->
 94         <dependency>
 95             <groupId>junit</groupId>
 96             <artifactId>junit</artifactId>
 97             <version>RELEASE</version>
 98             <!--test 說明這個包的存活是在test周期,也就是發布時將不包含這個jar包-->
 99             <scope>test</scope>
100         </dependency>
101         <!--spring單元測試依賴 -->
102         <dependency>
103             <groupId>org.springframework</groupId>
104             <artifactId>spring-test</artifactId>
105             <version>${spring.version}</version>
106             <scope>test</scope>
107         </dependency>
108         <!-- spring -->
109         <dependency>
110             <groupId>org.springframework</groupId>
111             <!-- 因依賴 會自動引入 spring-aop spring-beans spring-core spring-expression 四個包 -->
112             <artifactId>spring-context</artifactId>
113             <version>${spring.version}</version>
114         </dependency>
115         <dependency>
116             <groupId>org.springframework</groupId>
117             <artifactId>spring-context-support</artifactId>
118             <version>${spring.version}</version>
119         </dependency>
120         <dependency>
121             <groupId>org.springframework</groupId>
122             <artifactId>spring-aspects</artifactId>
123             <version>${spring.version}</version>
124         </dependency>
125         <dependency>
126             <groupId>org.springframework</groupId>
127             <artifactId>spring-tx</artifactId>
128             <version>${spring.version}</version>
129         </dependency>
130         <dependency>
131             <groupId>org.springframework</groupId>
132             <artifactId>spring-jdbc</artifactId>
133             <version>${spring.version}</version>
134         </dependency>
135         <!-- aspectj AOP -->
136         <dependency>
137             <groupId>org.aspectj</groupId>
138             <artifactId>aspectjrt</artifactId>
139             <version>${aspectj.version}</version>
140         </dependency>
141         <dependency>
142             <groupId>org.aspectj</groupId>
143             <artifactId>aspectjweaver</artifactId>
144             <version>${aspectj.version}</version>
145         </dependency>
146         <!-- 映入JSON jackson -->
147         <dependency>
148             <groupId>com.fasterxml.jackson.core</groupId>
149             <artifactId>jackson-annotations</artifactId>
150             <version>${jackson.version}</version>
151         </dependency>
152         <dependency>
153             <groupId>com.fasterxml.jackson.core</groupId>
154             <artifactId>jackson-databind</artifactId>
155             <version>${jackson.version}</version>
156         </dependency>
157         <dependency>
158             <groupId>com.fasterxml.jackson.core</groupId>
159             <artifactId>jackson-core</artifactId>
160             <version>${jackson.version}</version>
161         </dependency>
162         <dependency>
163             <groupId>com.fasterxml.jackson.dataformat</groupId>
164             <artifactId>jackson-dataformat-xml</artifactId>
165             <version>${jackson.version}</version>
166         </dependency>
167         <!-- 日志文件管理包 -->
168         <dependency>
169             <groupId>log4j</groupId>
170             <artifactId>log4j</artifactId>
171             <version>${log4j.version}</version>
172         </dependency>
173         <dependency>
174             <groupId>org.slf4j</groupId>
175             <artifactId>slf4j-api</artifactId>
176             <version>${slf4j.version}</version>
177         </dependency>
178         <dependency>
179             <groupId>org.slf4j</groupId>
180             <artifactId>slf4j-log4j12</artifactId>
181             <version>${slf4j.version}</version>
182         </dependency>
183     </dependencies>
184 
185     <dependencyManagement>
186         <dependencies>
187             <!--spring web-->
188             <dependency>
189                 <groupId>org.springframework</groupId>
190                 <artifactId>spring-web</artifactId>
191                 <version>${spring.version}</version>
192             </dependency>
193             <dependency>
194                 <groupId>org.springframework</groupId>
195                 <artifactId>spring-webmvc</artifactId>
196                 <version>${spring.version}</version>
197             </dependency>
198             <!--cglib-->
199             <dependency>
200                 <groupId>cglib</groupId>
201                 <artifactId>cglib</artifactId>
202                 <version>${cglib.version}</version>
203             </dependency>
204             <!-- mybatis -->
205             <dependency>
206                 <groupId>org.mybatis</groupId>
207                 <artifactId>mybatis</artifactId>
208                 <version>${mybatis.version}</version>
209             </dependency>
210             <dependency>
211                 <groupId>org.mybatis</groupId>
212                 <artifactId>mybatis-spring</artifactId>
213                 <version>${mybatisSpring.version}</version>
214             </dependency>
215             <!-- Mysql數據庫驅動包 -->
216             <dependency>
217                 <groupId>mysql</groupId>
218                 <artifactId>mysql-connector-java</artifactId>
219                 <version>${mysql.version}</version>
220             </dependency>
221             <!-- connection pool -->
222             <dependency>
223                 <groupId>com.alibaba</groupId>
224                 <artifactId>druid</artifactId>
225                 <version>${druid.version}</version>
226                 <!--<scope>runtime</scope>-->
227             </dependency>
228             <!--servlet-->
229             <dependency>
230                 <groupId>javax.servlet</groupId>
231                 <artifactId>javax.servlet-api</artifactId>
232                 <version>${javaxServlet.version}</version>
233                 <scope>provided</scope>
234             </dependency>
235             <dependency>
236                 <groupId>javax.servlet.jsp</groupId>
237                 <artifactId>jsp-api</artifactId>
238                 <version>${jspApi.version}</version>
239                 <scope>provided</scope>
240             </dependency>
241             <dependency>
242                 <groupId>javax.servlet</groupId>
243                 <artifactId>jstl</artifactId>
244                 <version>${jstl.version}</version>
245             </dependency>
246             <!-- 映入JSON lib -->
247             <dependency>
248                 <groupId>net.sf.json-lib</groupId>
249                 <artifactId>json-lib</artifactId>
250                 <version>${jsonLib.version}</version>
251                 <classifier>jdk15</classifier>
252             </dependency>
253             <!-- jackson old -->
254             <dependency>
255                 <groupId>org.codehaus.jackson</groupId>
256                 <artifactId>jackson-core-asl</artifactId>
257                 <version>${jacksonOld.version}</version>
258             </dependency>
259             <dependency>
260                 <groupId>org.codehaus.jackson</groupId>
261                 <artifactId>jackson-mapper-asl</artifactId>
262                 <version>${jacksonOld.version}</version>
263             </dependency>
264             <!-- 用dom4j解析xml文件 -->
265             <dependency>
266                 <groupId>dom4j</groupId>
267                 <artifactId>dom4j</artifactId>
268                 <version>${dom4j.version}</version>
269             </dependency>
270             <!-- ehcache -->
271             <dependency>
272                 <groupId>net.sf.ehcache</groupId>
273                 <artifactId>ehcache-core</artifactId>
274                 <version>${ehcacheCore.version}</version>
275             </dependency>
276             <dependency>
277                 <groupId>net.sf.ehcache</groupId>
278                 <artifactId>ehcache-web</artifactId>
279                 <version>${ehcacheWeb.version}</version>
280             </dependency>
281             <!-- 上傳組件包 -->
282             <dependency>
283                 <groupId>commons-fileupload</groupId>
284                 <artifactId>commons-fileupload</artifactId>
285                 <version>${commonsFileupload.version}</version>
286             </dependency>
287             <dependency>
288                 <groupId>commons-io</groupId>
289                 <artifactId>commons-io</artifactId>
290                 <version>${commonsIo.version}</version>
291             </dependency>
292             <dependency>
293                 <groupId>commons-codec</groupId>
294                 <artifactId>commons-codec</artifactId>
295                 <version>${commonsCodec.version}</version>
296             </dependency>
297             <dependency>
298                 <groupId>org.apache.commons</groupId>
299                 <artifactId>commons-collections4</artifactId>
300                 <version>${commonsCollections4.version}</version>
301             </dependency>
302             <dependency>
303                 <groupId>org.apache.commons</groupId>
304                 <artifactId>commons-lang3</artifactId>
305                 <version>3.3.2</version>
306             </dependency>
307             <!-- commons-beanutils -->
308             <dependency>
309                 <groupId>commons-beanutils</groupId>
310                 <artifactId>commons-beanutils</artifactId>
311                 <version>${commonsBeanutils.version}</version>
312                 <exclusions>
313                     <exclusion>
314                         <groupId>commons-logging</groupId>
315                         <artifactId>commons-logging</artifactId>
316                     </exclusion>
317                 </exclusions>
318             </dependency>
319             <!-- freemarker -->
320             <dependency>
321                 <groupId>org.freemarker</groupId>
322                 <artifactId>freemarker</artifactId>
323                 <version>${freemarker.version}</version>
324             </dependency>
325             <!-- poi -->
326             <dependency>
327                 <groupId>org.apache.poi</groupId>
328                 <artifactId>poi</artifactId>
329                 <version>${poi.version}</version>
330             </dependency>
331             <dependency>
332                 <groupId>org.apache.poi</groupId>
333                 <artifactId>poi-ooxml</artifactId>
334                 <version>${poi.version}</version>
335             </dependency>
336             <!-- org.apache.httpcomponents -->
337             <dependency>
338                 <groupId>org.apache.httpcomponents</groupId>
339                 <artifactId>httpcore</artifactId>
340                 <version>${httpcore.version}</version>
341             </dependency>
342             <dependency>
343                 <groupId>org.apache.httpcomponents</groupId>
344                 <artifactId>httpclient</artifactId>
345                 <version>${httpclient.version}</version>
346             </dependency>
347             <!-- com.sun.xml.ws/jaxws-rt -->
348             <dependency>
349                 <groupId>com.sun.xml.ws</groupId>
350                 <artifactId>jaxws-rt</artifactId>
351                 <version>${jaxwsRt.version}</version>
352             </dependency>
353             <!-- redis.clients/jedis -->
354             <dependency>
355                 <groupId>redis.clients</groupId>
356                 <artifactId>jedis</artifactId>
357                 <version>${jedis.version}</version>
358             </dependency>
359             <!-- com.rabbitmq/amqp-client -->
360             <dependency>
361                 <groupId>com.rabbitmq</groupId>
362                 <artifactId>amqp-client</artifactId>
363                 <version>${amqpClient.version}</version>
364             </dependency>
365             <!-- com.alibaba/fastjson -->
366             <dependency>
367                 <groupId>com.alibaba</groupId>
368                 <artifactId>fastjson</artifactId>
369                 <version>${fastjson.version}</version>
370             </dependency>
371             <!-- javax.annotation/jsr250-api -->
372             <dependency>
373                 <groupId>javax.annotation</groupId>
374                 <artifactId>jsr250-api</artifactId>
375                 <version>${jsr250.version}</version>
376             </dependency>
377         </dependencies>
378     </dependencyManagement>
379 
380     <build>
381         <plugins>
382             <!-- java編譯插件 -->
383             <plugin>
384                 <groupId>org.apache.maven.plugins</groupId>
385                 <artifactId>maven-compiler-plugin</artifactId>
386                 <version>3.2</version>
387                 <configuration>
388                     <source>1.8</source>
389                     <target>1.8</target>
390                     <encoding>UTF-8</encoding>
391                 </configuration>
392             </plugin>
393         </plugins>
394 
395         <pluginManagement>
396             <plugins>
397                 <!-- 配置Tomcat插件 -->
398                 <plugin>
399                     <groupId>org.apache.tomcat.maven</groupId>
400                     <artifactId>tomcat8-maven-plugin</artifactId>
401                     <version>3.0-r1756463</version>
402                 </plugin>
403             </plugins>
404         </pluginManagement>
405     </build>
406 
407 </project>

  2.web/pom.xml

  1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  3     <parent>
  4         <artifactId>solution</artifactId>
  5         <groupId>lm.solution</groupId>
  6         <version>1.0-SNAPSHOT</version>
  7     </parent>
  8     <modelVersion>4.0.0</modelVersion>
  9     <groupId>lm.solution</groupId>
 10     <artifactId>web</artifactId>
 11     <packaging>war</packaging>
 12     <version>1.0-SNAPSHOT</version>
 13     <name>web Maven Webapp</name>
 14     <url>http://maven.apache.org</url>
 15     <dependencies>
 16         <!--Module-->
 17         <dependency>
 18             <groupId>lm.solution</groupId>
 19             <artifactId>service</artifactId>
 20             <version>1.0-SNAPSHOT</version>
 21         </dependency>
 22         <dependency>
 23             <groupId>lm.solution</groupId>
 24             <artifactId>common</artifactId>
 25             <version>1.0-SNAPSHOT</version>
 26         </dependency>
 27 
 28         <!--Libary-->
 29         <!--spring mvc-->
 30         <dependency>
 31             <groupId>org.springframework</groupId>
 32             <artifactId>spring-webmvc</artifactId>
 33         </dependency>
 34         <!--cglib-->
 35         <dependency>
 36             <groupId>cglib</groupId>
 37             <artifactId>cglib</artifactId>
 38         </dependency>
 39         <!-- mybatis核心包 -->
 40         <dependency>
 41             <groupId>org.mybatis</groupId>
 42             <artifactId>mybatis</artifactId>
 43         </dependency>
 44         <!--mybatis spring 插件 -->
 45         <dependency>
 46             <groupId>org.mybatis</groupId>
 47             <artifactId>mybatis-spring</artifactId>
 48         </dependency>
 49         <!-- Mysql數據庫驅動包 -->
 50         <dependency>
 51             <groupId>mysql</groupId>
 52             <artifactId>mysql-connector-java</artifactId>
 53         </dependency>
 54         <!-- connection pool -->
 55         <dependency>
 56             <groupId>com.alibaba</groupId>
 57             <artifactId>druid</artifactId>
 58             <!--<scope>runtime</scope>-->
 59         </dependency>
 60         <!--servlet-->
 61         <dependency>
 62             <groupId>javax.servlet</groupId>
 63             <artifactId>javax.servlet-api</artifactId>
 64             <scope>provided</scope>
 65         </dependency>
 66         <dependency>
 67             <groupId>javax.servlet.jsp</groupId>
 68             <artifactId>jsp-api</artifactId>
 69             <scope>provided</scope>
 70         </dependency>
 71         <dependency>
 72             <groupId>javax.servlet</groupId>
 73             <artifactId>jstl</artifactId>
 74         </dependency>
 75         <!-- 映入JSON lib -->
 76         <dependency>
 77             <groupId>net.sf.json-lib</groupId>
 78             <artifactId>json-lib</artifactId>
 79             <classifier>jdk15</classifier>
 80         </dependency>
 81         <!-- 用dom4j解析xml文件 -->
 82         <dependency>
 83             <groupId>dom4j</groupId>
 84             <artifactId>dom4j</artifactId>
 85         </dependency>
 86         <!-- ehcache -->
 87         <dependency>
 88             <groupId>net.sf.ehcache</groupId>
 89             <artifactId>ehcache-core</artifactId>
 90         </dependency>
 91         <dependency>
 92             <groupId>net.sf.ehcache</groupId>
 93             <artifactId>ehcache-web</artifactId>
 94         </dependency>
 95         <!-- 上傳組件包 -->
 96         <dependency>
 97             <groupId>commons-fileupload</groupId>
 98             <artifactId>commons-fileupload</artifactId>
 99         </dependency>
100         <dependency>
101             <groupId>commons-io</groupId>
102             <artifactId>commons-io</artifactId>
103         </dependency>
104         <!-- common others -->
105         <dependency>
106             <groupId>commons-codec</groupId>
107             <artifactId>commons-codec</artifactId>
108         </dependency>
109         <dependency>
110             <groupId>org.apache.commons</groupId>
111             <artifactId>commons-collections4</artifactId>
112         </dependency>
113         <dependency>
114             <groupId>org.apache.commons</groupId>
115             <artifactId>commons-lang3</artifactId>
116         </dependency>
117         <!-- commons-beanutils -->
118         <dependency>
119             <groupId>commons-beanutils</groupId>
120             <artifactId>commons-beanutils</artifactId>
121             <exclusions>
122                 <exclusion>
123                     <groupId>commons-logging</groupId>
124                     <artifactId>commons-logging</artifactId>
125                 </exclusion>
126             </exclusions>
127         </dependency>
128         <!-- freemarker -->
129         <dependency>
130             <groupId>org.freemarker</groupId>
131             <artifactId>freemarker</artifactId>
132         </dependency>
133         <!-- org.apache.httpcomponents -->
134         <dependency>
135             <groupId>org.apache.httpcomponents</groupId>
136             <artifactId>httpcore</artifactId>
137         </dependency>
138         <dependency>
139             <groupId>org.apache.httpcomponents</groupId>
140             <artifactId>httpclient</artifactId>
141         </dependency>
142         <!-- redis.clients/jedis -->
143         <dependency>
144             <groupId>redis.clients</groupId>
145             <artifactId>jedis</artifactId>
146         </dependency>
147         <!-- com.rabbitmq/amqp-client -->
148         <dependency>
149             <groupId>com.rabbitmq</groupId>
150             <artifactId>amqp-client</artifactId>
151         </dependency>
152         <!-- com.alibaba/fastjson -->
153         <dependency>
154             <groupId>com.alibaba</groupId>
155             <artifactId>fastjson</artifactId>
156         </dependency>
157     </dependencies>
158     <build>
159         <finalName>web</finalName>
160 
161         <plugins>
162             <plugin>
163                 <groupId>org.apache.tomcat.maven</groupId>
164                 <artifactId>tomcat8-maven-plugin</artifactId>
165             </plugin>
166         </plugins>
167     </build>
168 </project>

二、web 配置

  在 java config 配置方式中,我們就不需要在 web.xml 中配置監聽及servlet 等節點了,這里我們仍然使用 servlet 3.0 API 。

  1.web.xml

 1 <!DOCTYPE web-app PUBLIC
 2         "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 3         "http://java.sun.com/dtd/web-app_2_3.dtd" >
 4 
 5 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 6          xmlns="http://java.sun.com/xml/ns/javaee"
 7          xsi:schemaLocation="
 8             http://java.sun.com/xml/ns/javaee
 9             http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
10          id="WebApp_ID"
11          version="3.0">
12 </web-app>

三、用 JavaConfig 替代 web.xml 中 servlet 配置及監聽配置

  public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer:  

    WebInitializer繼承關系鏈:

    WebInitializer -->AbstractAnnotationConfigDispatcherServletInitializer -->AbstractDispatcherServletInitializer -->

    AbstractContextLoaderInitializer -->WebApplicationInitializer

    實現 WebApplicationInitializer 接口,就等同於 web.xml 配置

    @Override public void onStartup :

      web.xml 核心的相關配置,可再此方法中重寫 自定義的配置 ,如:<filter> 可用 FilterRegistration.Dynamic encodingFilter 此種方式來配置。

    @Override protected Class<?>[] getRootConfigClasses :

      重寫此方法,以替代 spring-context.xml ,在這個方法中返回的 類類型數組 可配置上下文中需要的 bean ,如數據庫,緩存 等等。

    @Override protected Class<?>[] getServletConfigClasses:

      重寫此方法,以替代 spring-mvc.xml ,在這個方法中返回的類型數組 可配置 spring 中 視圖解析器,http message converter 等框架需要的 bean。

    @Override protected String[] getServletMappings :      

      重寫此方法,就相當於 <servlet-mapping> 節點等同的功能,可指定 站點根路徑。

  public class WebConfig extends WebMvcConfigurerAdapter :

    @EnableWebMvc:注解會開啟一些默認配置,如:ViewResolver MessageConverter 等,若無此注解,重寫 WebMvcConfigurerAdapter 方法無效。

    @ComponentScan:會掃描指定包中的類,根據注解,將特定類初始化為 上下文中需要的 bean 。

    @Override public void addViewControllers :

      重寫 addViewControllers 簡化頁面快捷轉向,這樣就可以不用配置 Controller 了(就是那些僅返回一個頁面路徑的簡單 controller )。

    @Bean public InternalResourceViewResolver viewResolver :

      配置JSP視圖解析器

    @Bean public MultipartResolver multipartResolver :

      配置springMVC處理上傳文件的信息

    @Override public void addResourceHandlers :

      配置靜態文件處理

  1.WebInitializer.java

 1 package lm.solution.web.config;
 2 
 3 import lm.solution.web.config.configs.RootConfig;
 4 import lm.solution.web.config.configs.WebConfig;
 5 import org.springframework.web.filter.CharacterEncodingFilter;
 6 import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
 7 
 8 import javax.servlet.*;
 9 
10 /**
11  * WebInitializer繼承關系鏈:
12  * WebInitializer -->
13  * AbstractAnnotationConfigDispatcherServletInitializer  -->
14  * AbstractDispatcherServletInitializer  -->
15  * AbstractContextLoaderInitializer  -->
16  * WebApplicationInitializer
17  * 實現 WebApplicationInitializer 接口,就等同於 web.xml 配置
18  * */
19 public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
20 
21     @Override
22     public void onStartup(ServletContext servletContext)
23             throws ServletException{
24 
25         /**
26          * super 中已設置 servlet.setLoadOnStartup(1)
27          * */
28         super.onStartup(servletContext);
29 
30         //
31         ServletRegistration servletRegistration =servletContext.getServletRegistration("dispatcher");
32 
33         // spring 字符過濾
34         FilterRegistration.Dynamic encodingFilter=servletContext.addFilter("encoding-filter",CharacterEncodingFilter.class);
35         encodingFilter.setInitParameter("encoding","UTF-8");
36         encodingFilter.setInitParameter("forceEncoding","true");
37         encodingFilter.setAsyncSupported(true);
38         encodingFilter.addMappingForUrlPatterns(null,true,"/*");
39 
40 
41     }
42 
43     // root配置類初始化
44     // 指定 Root WebApplicationContext 類,這個類必須@Configuration來注解,從而代替XML配置文件
45     @Override
46     protected Class<?>[] getRootConfigClasses() {
47 
48         return new Class<?>[]{RootConfig.class};
49 
50     }
51 
52     // web配置類初始化
53     // 指定 Servlet WebApplicationContext 類,這個類必須@Configuration來注解,從而代替XML配置文件
54     @Override
55     protected Class<?>[] getServletConfigClasses() {
56 
57         return new Class<?>[]{WebConfig.class};
58 
59     }
60 
61     // 映射根路徑初始化
62     // 指定 Servlet mappings
63     @Override
64     protected String[] getServletMappings() {
65 
66         return new String[]{"/"};
67 
68     }
69 
70     @Override
71     protected Filter[] getServletFilters() {
72 
73         return null;
74 
75     }
76 
77     @Override
78     protected void customizeRegistration(ServletRegistration.Dynamic registration){
79 
80         // 讓404作為異常拋出 不使用tomcat默認的
81         registration.setInitParameter("throwExceptionIfNoHandlerFound","true");
82 
83     }
84 
85 }

  2.WebConfig.java

  1 package lm.solution.web.config.configs;
  2 
  3 import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
  4 import lm.solution.common.web.messageconverter.CustomMessageConverter;
  5 import lm.solution.web.config.beans.TimerInterceptor;
  6 import org.springframework.context.annotation.Bean;
  7 import org.springframework.context.annotation.ComponentScan;
  8 import org.springframework.context.annotation.Configuration;
  9 import org.springframework.http.MediaType;
 10 import org.springframework.http.converter.HttpMessageConverter;
 11 import org.springframework.web.multipart.MultipartResolver;
 12 import org.springframework.web.multipart.commons.CommonsMultipartResolver;
 13 import org.springframework.web.servlet.config.annotation.*;
 14 import org.springframework.web.servlet.view.InternalResourceViewResolver;
 15 import org.springframework.web.servlet.view.JstlView;
 16 
 17 import java.util.ArrayList;
 18 import java.util.List;
 19 
 20 @Configuration
 21 /**
 22  * @EnableWebMvc 注解會開啟一些默認配置,如:ViewResolver MessageConverter 等,
 23  * 若無此注解,重寫 WebMvcConfigurerAdapter 方法無效
 24  * */
 25 @EnableWebMvc
 26 @ComponentScan(value = {
 27         "lm.solution.web",
 28         "lm.solution.service.mysql",
 29         "lm.solution.service.webtest"
 30 })
 31 /**
 32  * 繼承 WebMvcConfigurerAdapter 類,重寫其方法可對 spring mvc 進行配置
 33  * */
 34 public class WebConfig extends WebMvcConfigurerAdapter {
 35 
 36     // 重寫 addViewControllers 簡化頁面快捷轉向,這樣就可以不用配置 Controller 了
 37     @Override
 38     public void addViewControllers(ViewControllerRegistry registry) {
 39 
 40         registry.addViewController("/").setViewName("index");
 41         registry.addViewController("/error").setViewName("error/error");
 42         registry.addViewController("/excel").setViewName("excel/excel");
 43         // 文件上傳下載
 44         registry.addViewController("/upload").setViewName("fileupload/upload");
 45         registry.addViewController("/ImageValidateCodeLogin").setViewName("login/imageValidateCodeLogin");
 46         registry.addViewController("/restfulapi").setViewName("restful/user");
 47         registry.addViewController("/jaxwsri").setViewName("jaxwsri/wsri");
 48         registry.addViewController("/redis").setViewName("redis/jedis");
 49         registry.addViewController("/mybatisPage").setViewName("db/mybatis");
 50         registry.addViewController("/messageconverter").setViewName("httpmessageconverter/customconverter");
 51         registry.addViewController("/sse").setViewName("serverpushmessage/sse");
 52 
 53     }
 54 
 55     // 配置JSP視圖解析器
 56     @Bean
 57     public InternalResourceViewResolver viewResolver() {
 58         InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
 59         /**
 60          * views 在 /resources/ 下
 61          * */
 62         // 前綴
 63         viewResolver.setPrefix("/WEB-INF/classes/views/");
 64         // 后綴
 65         viewResolver.setSuffix(".jsp");
 66         viewResolver.setViewClass(JstlView.class);
 67         viewResolver.setContentType("text/html");
 68         // 可以在JSP頁面中通過${}訪問beans
 69         viewResolver.setExposeContextBeansAsAttributes(true);
 70         return viewResolver;
 71     }
 72 
 73     // 配置springMVC處理上傳文件的信息
 74     @Bean
 75     public MultipartResolver multipartResolver() {
 76         CommonsMultipartResolver resolver = new CommonsMultipartResolver();
 77         resolver.setDefaultEncoding("UTF-8");
 78         resolver.setMaxUploadSize(10485760000L);
 79         resolver.setMaxInMemorySize(40960);
 80         return resolver;
 81     }
 82 
 83     // 配置靜態文件處理
 84     @Override
 85     public void addResourceHandlers(ResourceHandlerRegistry registry){
 86 
 87         /**
 88          * addResourceHandler 指的是對外暴露的訪問路徑
 89          * addResourceLocations 指的是文件放置的目錄
 90          * */
 91         registry.addResourceHandler("/assets/**")
 92                 .addResourceLocations("classpath:/assets/");
 93 
 94         // href 鏈接方式 下載文件
 95         registry.addResourceHandler("/files/**")
 96                 .addResourceLocations("classpath:/files/");
 97 
 98         /**
 99          * 解決 No handler found for GET /favicon.ico 異常
100          * */
101         registry.addResourceHandler("/favicon.ico")
102                 .addResourceLocations("classpath:/favicon.ico");
103 
104     }
105 
106     // 重寫 configurePathMatch ,改變路徑參數匹配
107     @Override
108     public void configurePathMatch(PathMatchConfigurer configurer) {
109 
110         /**
111          * Spring mvc 默認 如果路徑參數后面帶點,如 “/mm/nn/xx.yy” 后面的yy值將被忽略
112          * 加入下面的配置,就不會忽略“.”后面的參數了
113          * */
114         configurer.setUseSuffixPatternMatch(false);
115 
116     }
117 
118 //
119 //    // 負責讀取二進制格式的數據和寫出二進制格式的數據;
120 //    @Bean
121 //    public ByteArrayHttpMessageConverter byteArrayHttpMessageConverter() {
122 //
123 //        return new ByteArrayHttpMessageConverter();
124 //
125 //    }
126 //
127 //    // 負責讀取字符串格式的數據和寫出字符串格式的數據;
128 //    @Bean
129 //    public StringHttpMessageConverter stringHttpMessageConverter() {
130 //
131 //        StringHttpMessageConverter messageConverter = new StringHttpMessageConverter();
132 //        messageConverter.setDefaultCharset(Charset.forName("UTF-8"));
133 //        return messageConverter;
134 //
135 //    }
136 //
137 //    // 負責讀取資源文件和寫出資源文件數據;
138 //    @Bean
139 //    public ResourceHttpMessageConverter resourceHttpMessageConverter() {
140 //
141 //        return new ResourceHttpMessageConverter();
142 //
143 //    }
144 //
145 //    /**
146 //     * 負責讀取form提交的數據
147 //     * 能讀取的數據格式為 application/x-www-form-urlencoded,
148 //     * 不能讀取multipart/form-data格式數據;
149 //     * 負責寫入application/x-www-from-urlencoded和multipart/form-data格式的數據;
150 //     */
151 //    @Bean
152 //    public FormHttpMessageConverter formHttpMessageConverter() {
153 //
154 //        return new FormHttpMessageConverter();
155 //
156 //    }
157 //
158 //    // 負責讀取和寫入json格式的數據;
159 //    /**
160 //     * 配置 fastjson 中實現 HttpMessageConverter 接口的轉換器
161 //     * FastJsonHttpMessageConverter 是 fastjson 中實現了 HttpMessageConverter 接口的類
162 //     */
163 //    @Bean(name = "fastJsonHttpMessageConverter")
164 //    public FastJsonHttpMessageConverter fastJsonHttpMessageConverter() {
165 //        //
166 //        String txtHtml = "text/html;charset=UTF-8";
167 //        String txtJson = "text/json;charset=UTF-8";
168 //        String appJson = "application/json;charset=UTF-8";
169 //
170 //        // 這里順序不能反,一定先寫 text/html,不然 IE 下會出現下載提示
171 //        List<MediaType> mediaTypes = new ArrayList<>();
172 //        mediaTypes.add(MediaType.parseMediaType(txtHtml));
173 //        mediaTypes.add(MediaType.parseMediaType(txtJson));
174 //        mediaTypes.add(MediaType.parseMediaType(appJson));
175 //
176 //        // 加入支持的媒體類型,返回 contentType
177 //        FastJsonHttpMessageConverter fastjson = new FastJsonHttpMessageConverter();
178 //        fastjson.setSupportedMediaTypes(mediaTypes);
179 //        return fastjson;
180 //
181 //    }
182 //
183 //    // 負責讀取和寫入 xml 中javax.xml.transform.Source定義的數據;
184 //    @Bean
185 //    public SourceHttpMessageConverter sourceHttpMessageConverter() {
186 //
187 //        return new SourceHttpMessageConverter();
188 //
189 //    }
190 //
191 //    // 負責讀取和寫入xml 標簽格式的數據;
192 //    @Bean
193 //    public Jaxb2RootElementHttpMessageConverter jaxb2RootElementHttpMessageConverter() {
194 //
195 //        return new Jaxb2RootElementHttpMessageConverter();
196 //
197 //    }
198 //
199 //    // 注冊消息轉換器
200 //    /**
201 //     * 重寫 configureMessageConverters 會覆蓋掉 spring mvc 默認注冊的多個 HttpMessageConverter
202 //     * 所以 推薦使用 extendMessageConverter
203 //     * */
204 //    /**
205 //     * Error:
206 //     * 400:(錯誤請求) 服務器不理解請求的語法。
207 //     * 415:(不支持的媒體類型) 請求的格式不受請求頁面的支持。
208 //     */
209 //    @Override
210 //    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
211 //
212 //        converters.add(this.byteArrayHttpMessageConverter());
213 //        converters.add(this.stringHttpMessageConverter());
214 //        converters.add(this.resourceHttpMessageConverter());
215 //        converters.add(this.formHttpMessageConverter());
216 //        converters.add(this.fastJsonHttpMessageConverter());
217 //        converters.add(this.sourceHttpMessageConverter());
218 //        converters.add(this.jaxb2RootElementHttpMessageConverter());
219 //
220 //    }
221 
222     // 自定義 HttpMessageConverter
223     @Bean
224     public CustomMessageConverter customMessageConverter(){
225 
226         return new CustomMessageConverter();
227 
228     }
229 
230     // 負責讀取和寫入json格式的數據;
231     /**
232      * 配置 fastjson 中實現 HttpMessageConverter 接口的轉換器
233      * FastJsonHttpMessageConverter 是 fastjson 中實現了 HttpMessageConverter 接口的類
234      */
235     @Bean(name = "fastJsonHttpMessageConverter")
236     public FastJsonHttpMessageConverter fastJsonHttpMessageConverter() {
237         //
238         String txtHtml = "text/html;charset=UTF-8";
239         String txtJson = "text/json;charset=UTF-8";
240         String appJson = "application/json;charset=UTF-8";
241 
242         // 這里順序不能反,一定先寫 text/html,不然 IE 下會出現下載提示
243         List<MediaType> mediaTypes = new ArrayList<>();
244         mediaTypes.add(MediaType.parseMediaType(txtHtml));
245         mediaTypes.add(MediaType.parseMediaType(txtJson));
246         mediaTypes.add(MediaType.parseMediaType(appJson));
247 
248         // 加入支持的媒體類型,返回 contentType
249         FastJsonHttpMessageConverter fastjson = new FastJsonHttpMessageConverter();
250         fastjson.setSupportedMediaTypes(mediaTypes);
251         return fastjson;
252 
253     }
254 
255     /**
256      * 重寫 extendMessageConverters 方法,僅添加自定義 HttpMessageConverter
257      * 不覆蓋默認注冊的 HttpMessageConverter
258      * */
259     @Override
260     public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
261 
262         converters.add(customMessageConverter());
263         converters.add(fastJsonHttpMessageConverter());
264 
265     }
266 
267     // 攔截器 bean
268     @Bean
269     public TimerInterceptor timerInterceptor(){
270 
271         return new TimerInterceptor();
272 
273     }
274 
275     // 重寫 addInterceptors 注冊攔截器
276     @Override
277     public void addInterceptors(InterceptorRegistry registry) {
278 
279         registry.addInterceptor(timerInterceptor());
280 
281     }
282 
283 }

  3.RootConfig.java

 1 package lm.solution.web.config.configs;
 2 
 3 import lm.solution.web.config.beans.MySqlBean;
 4 import lm.solution.web.config.beans.RedisBean;
 5 import org.springframework.context.annotation.Configuration;
 6 import org.springframework.context.annotation.Import;
 7 import lm.solution.web.config.beans.HandlerBean;
 8 
 9 @Configuration
10 @Import({
11         RedisBean.class,
12         MySqlBean.class,
13         HandlerBean.class
14 })
15 public class RootConfig {
16     /**
17      * 此處管理 Beans
18      * */
19 }

 

 

 

 

                                         蒙

                                    2018-05-20 23:46 周日

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM