Gradle - Spring 4 Exemple MVC Hello World - Annotation

Gradle - Exemple Spring 4 MVC Hello World - Annotation

gradle-spring-logo

Dans ce tutoriel, nous allons reprendre lesGradle + Spring MVC XML example précédents, les réécrire pour prendre en charge la configuration d'annotation @JavaConfig, plus de fichiers XML.

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

Technologies utilisées:

  1. Gradle 2.0

  2. Spring 4.1.6.RELEASE

  3. Tomcat 7 ou Jetty 9

  4. Eclipse 4.4

  5. JDK 1.7

  6. Logback 1.1.3

  7. Boostrap 3

1. Structure du projet

Téléchargez le projetsource code et vérifiez la structure des dossiers du projet:

spring4-mvc-gradle-project-anno

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. Maintenant, vous pouvez importer le projet dans Eclipse IDE.

your-project$ gradle eclipse

3. Printemps @Configuration

Spring @Configuration et son équivalent XML.

3.1 Spring annotation configuration to scan the service classes.

SpringRootConfig.java

package com.example.helloworld.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan({ "com.example.helloworld.service" })
public class SpringRootConfig {
}

Équivalent XML.

spring-core-config.xml



    

3.2 Extends abstract class WebMvcConfigurerAdapter.

SpringWebConfig.java

package com.example.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 //
@Configuration
@ComponentScan({ "com.example.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;
    }

}

Équivalent XML.

spring-web-config.xml



    

    
        
        
        
    

    

    

4. Conteneur Servlet 3.0+

Créez une classeServletInitializer, le conteneur Servlet 3.0+ récupérera cette classe et l'exécutera automatiquement. Ceci est la classe de remplacement pourweb.xml

package com.example.helloworld.servlet3;

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

import com.example.helloworld.config.SpringRootConfig;
import com.example.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[] { "/" };
    }

}

Équivalent XML.

web.xml



    Gradle + Spring MVC Hello World
    Spring MVC web application

    
    
        hello-dispatcher
        
            org.springframework.web.servlet.DispatcherServlet
        
        
            contextConfigLocation
            /WEB-INF/spring-mvc-config.xml
        
        1
    

    
        hello-dispatcher
        /
    

    
    
        
            org.springframework.web.context.ContextLoaderListener
        
    

    
        contextConfigLocation
        /WEB-INF/spring-core-config.xml
    

Note
Il n'y a pas de changement dans le contrôleur Spring, les fichiers de journalisation et JSP, donc, le code source ne se répétera pas ici, veuillez vous référer auxGradle + Spring MVC XML exampleprécédents pour le code source complet.

5. Demo

5.1 To run this project. Problèmegradle jettyRun pour démarrer le conteneur Jetty intégré.

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

spring-4-mvc-gradle-demo1

spring4-mvc-gradle-demo2

Télécharger le code source