In this tutorial, we will take the previous Gradle + Spring MVC XML example, rewrite it to support @JavaConfig annotation configuration, no more XML files.

P.S This example will works in Servlet 3.0+ container only, like Tomcat 7 or Jetty 9.

Technologies used :

  • Gradle 2.0
  • Spring 4.1.6.RELEASE
  • Tomcat 7 or Jetty 9
  • Eclipse 4.4
  • JDK 1.7
  • Logback 1.1.3
  • Boostrap 3

1. Project Structure

Download the project source code and review the project folder structure :

P.S No more XML files like web.xml or Spring XML configuration files.

2. Gradle

2.1 Review the build.gradle file, this should be self-explanatory.

build.gradle

apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'eclipse-wtp'
//apply plugin: 'jetty' //too old, Jetty 6, use gretty plugin
apply plugin: 'org.akhikhl.gretty' // JDK 7
sourceCompatibility = 1.7
targetCompatibility = 1.7 repositories {
mavenLocal()
mavenCentral()
} dependencies {
compile 'ch.qos.logback:logback-classic:1.1.3'
compile 'org.springframework:spring-webmvc:4.1.6.RELEASE'
compile 'javax.servlet:jstl:1.2' //include in compile only, exclude in the war
providedCompile 'javax.servlet:servlet-api:2.5'
} //Gretty Embedded Jetty
buildscript {
repositories {
jcenter()
} dependencies {
classpath 'org.akhikhl.gretty:gretty:+'
}
} // Don't use Jetty8, even it's a servlet 3.0+ container,
// but not support non-jar WebApplicationInitializer scanning.
// It will cause "No Spring WebApplicationInitializer types detected on classpath"
gretty {
port = 8080
contextPath = 'spring4'
servletContainer = 'jetty9' //tomcat7 or tomcat8
} //For Eclipse IDE only
eclipse { wtp {
component { //define context path, default to project folder name
contextPath = 'spring4' } }
}

2.2 Make this project supports Eclipse IDE. Now, you can import the project into Eclipse IDE.


your-project$ gradle eclipse

3. Spring @Configuration

Spring @Configuration and its XML equivalent.

3.1 Spring annotation configuration to scan the service classes.

SpringRootConfig.java

package com.mkyong.helloworld.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration; @Configuration
@ComponentScan({ "com.mkyong.helloworld.service" })
public class SpringRootConfig {
}

XML equivalent.

spring-core-config.xml

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd "> <context:component-scan base-package="com.mkyong.helloworld.service" /> </beans>

3.2 Extends abstract class WebMvcConfigurerAdapter.

SpringWebConfig.java

package com.mkyong.helloworld.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView; @EnableWebMvc //<mvc:annotation-driven />
@Configuration
@ComponentScan({ "com.mkyong.helloworld.web" })
public class SpringWebConfig extends WebMvcConfigurerAdapter { @Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**")
.addResourceLocations("/resources/");
} @Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver
= new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/jsp/");
viewResolver.setSuffix(".jsp");
return viewResolver;
} }

XML equivalent.

spring-web-config.xml

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd "> <context:component-scan base-package="com.mkyong.helloworld.web" /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/views/jsp/" />
<property name="suffix" value=".jsp" />
</bean> <mvc:resources mapping="/resources/**" location="/resources/" /> <mvc:annotation-driven /> </beans>

4. Servlet 3.0+ Container

Create a ServletInitializer class, Servlet 3.0+ container will pick up this class and run it automatically. This is the replacement class for web.xml

package com.mkyong.helloworld.servlet3;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import com.mkyong.helloworld.config.SpringRootConfig;
import com.mkyong.helloworld.config.SpringWebConfig; public class MyWebInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer { @Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { SpringRootConfig.class };
} @Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { SpringWebConfig.class };
} @Override
protected String[] getServletMappings() {
return new String[] { "/" };
} }

XML equivalent.

web.xml

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5"> <display-name>Gradle + Spring MVC Hello World</display-name>
<description>Spring MVC web application</description> <!-- For web context -->
<servlet>
<servlet-name>hello-dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-mvc-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet> <servlet-mapping>
<servlet-name>hello-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping> <!-- For root context -->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener> <context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-core-config.xml</param-value>
</context-param> </web-app>

Note

There is no change in the Spring controller, logback and JSP files, so, the source code will not repeat here, please refer to the previous Gradle + Spring MVC XML example for complete source code.

5. Demo

5.1 To run this project. Issues gradle jettyRun to start the embedded Jetty container.

Terminal

your-project$ gradle jettyRun

21:56:34 INFO  Jetty 9.2.10.v20150310 started and listening on port 8080
21:56:34 INFO spring4 runs at:
21:56:34 INFO http://localhost:8080/spring4
Press any key to stop the server.
> Building 87% > :jettyRun

5.2 http://localhost:8080/spring4/

5.3 http://localhost:8080/spring4/hello/mkyong.com

Gradle – Spring 4 MVC Hello World Example – Annotation的更多相关文章

  1. Gradle – Spring 4 MVC Hello World Example

    In this tutorial, we will show you a Gradle + Spring 4 MVC, Hello World Example (JSP view), XML conf ...

  2. Spring Boot——2分钟构建spring web mvc REST风格HelloWorld

    之前有一篇<5分钟构建spring web mvc REST风格HelloWorld>介绍了普通方式开发spring web mvc web service.接下来看看使用spring b ...

  3. [转]Spring Boot——2分钟构建spring web mvc REST风格HelloWorld

    Spring Boot——2分钟构建spring web mvc REST风格HelloWorld http://projects.spring.io/spring-boot/ http://spri ...

  4. Spring Framework------>version4.3.5.RELAESE----->Reference Documentation学习心得----->Spring Framework中的spring web MVC模块

    spring framework中的spring web MVC模块 1.概述 spring web mvc是spring框架中的一个模块 spring web mvc实现了web的MVC架构模式,可 ...

  5. spring 3 mvc hello world + mavern +jetty

    Spring 3 MVC hello world example By mkyong | August 2, 2011 | Updated : June 15, 2015 In this tutori ...

  6. Spring 3 MVC: Themes In Spring-Tutorial With Example---reference

    Welcome to Part 6 of Spring 3.0 MVC Series. In previous article we saw how to add Internationalizati ...

  7. Spring 4 MVC+Hibernate 4+MySQL+Maven使用注解集成实例

    Spring 4 MVC+Hibernate 4+MySQL+Maven使用注解集成实例 转自:通过注解的方式集成Spring 4 MVC+Hibernate 4+MySQL+Maven,开发项目样例 ...

  8. Spring Web MVC(三)之注解

    [toc] spring web mvc 基于注解的优化 我写的注解是按照spring web的部件分类写的,这样的话比较方便查看,大家感觉有用的话可以分享个别人,希望对对更多的人有帮助.毕竟零基础开 ...

  9. Spring 4 MVC example with Maven

    In this tutorial, we show you a Spring 4 MVC example, using Maven build tool. Technologies used : Sp ...

随机推荐

  1. POJ 1966 Cable TV Network (无向图点连通度)

    [题意]给出一个由n个点,m条边组成的无向图.求最少去掉多少点才能使得图中存在两点,它们之间不连通. [思路]回想一下s->t的最小点割,就是去掉多少个点能使得s.t不连通.那么求点连通度就枚举 ...

  2. 推荐 15 个 Angular.js 应用扩展指令(参考应用)

    几天前我们看到Angular 1.4.0发布了-一个以社团为驱动的发布版本涵盖了400多个GitHub的提交,增加了对特性的提升,比如动画,以及可用性. 官方新闻发布稿 覆盖了绝大部分,这同样值得放于 ...

  3. Nginx & AWStats 安装、配置、使用

    —— 参考IBM文章:THIS , 不一样的指导顺序 —— 1. awstats分析nginx - access.log,网上资料大部分都是下载,然后配置.官网下载地址: http://awstats ...

  4. H264中的SPS、PPS提取与作用

    牛逼的视频会议网站:http://wmnmtm.blog.163.com/blog/#m=0 ++++++++++++++++++++++++++++++++++++++++++++++++++++ ...

  5. Liunx系统学习一,liunx系统的目录结构及含义

    LIUNX系统目录结构: “/” ===>这是linux文件系统的入口,也是整个linux文件系统的根目录,linux不同于windows,没有所谓的C,D,E盘,整个liunx只有一个根分区 ...

  6. Delphi打开窗体时报"Corrupt Portfolio Stream"

      今天在打开一个Delphi窗体时报了这么一个错误: Corrupt Portfolio Stream 查了一下,主要是由于Delphi窗体的*.ddp文件损坏引起的. 解决方法: 删除.ddp 文 ...

  7. Oracle 课程三之表设计

    完成本课程的学习后,您应该能够: •普通堆表优点和缺点 •理解rowid •全局临时表优点.缺点和适用场景 •分区表的类型和原理.优点和缺点.适用场景 •表字段的高效设计 •sequence的设计   ...

  8. win7和centos双系统安装

    几年之前为了安装xp和linux的双系统曾折腾了好多天,今天为了安装这个win7和centos双系统,也折腾了两天多,哦,我的天,安装个双系统,怎么这么麻烦呢? 没有来得及整理,先铺上草稿,供同志们参 ...

  9. POJ 3067 Japan

    Japan Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 25489   Accepted: 6907 Descriptio ...

  10. java多线程学习笔记——详细

    一.线程类  1.新建状态(New):新创建了一个线程对象.        2.就绪状态(Runnable):线程对象创建后,其他线程调用了该对象的start()方法.该状态的线程位于可运行线程池中, ...