Gradle - Spring 4 MVC Hello Worldの例 - 注釈

Gradle – Spring 4 MVC Hello Worldの例–注釈

gradle-spring-logo

このチュートリアルでは、前のGradle + Spring MVC XML exampleを取得し、@ JavaConfigアノテーション構成をサポートするように書き直し、XMLファイルを追加しません。

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

使用される技術:

  1. Gradle 2.0

  2. 春4.1.6。リリース

  3. Tomcat 7またはJetty 9

  4. Eclipse 4.4

  5. JDK 1.7

  6. ログバック1.1.3

  7. ブーストラップ3

1. プロジェクト構造

プロジェクトsource codeをダウンロードし、プロジェクトのフォルダー構造を確認します。

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. これで、プロジェクトをEclipse IDEにインポートできます。

your-project$ gradle eclipse

3. Spring @Configuration

Spring @Configurationとそれに相当する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 {
}

同等の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;
    }

}

同等のXML。

spring-web-config.xml



    

    
        
        
        
    

    

    

4. サーブレット3.0+コンテナ

ServletInitializerクラスを作成すると、サーブレット3.0以降のコンテナがこのクラスを取得して自動的に実行します。 これはweb.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[] { "/" };
    }

}

同等の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
Springコントローラー、ログバック、JSPファイルに変更はないため、ここではソースコードは繰り返されません。完全なソースコードについては、前のGradle + Spring MVC XML exampleを参照してください。

5. Demo

5.1 To run this project. gradle jettyRunを発行して、組み込みJettyコンテナーを開始します。

ターミナル

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

ソースコードをダウンロード

ダウンロード–spring4-mvc-gradle-annotation-hello-world.zip(39 KB)