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. Затмение 4.4

  5. JDK 1,7

  6. Logback 1.1.3

  7. Boostrap 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 и его 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, контейнер Servlet 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

Скачать исходный код