Alexey Zvolinskiy

About Alexey Zvolinskiy

Alexey is a test developer with solid experience in automation of web-applications using Java, TestNG and Selenium. He is so much into QA that even after work he provides training courses for junior QA engineers.

Spring Boot: Fast MVC start

Spring-Boot-MVC-Gradle-300x300

I was planning to write an article about Spring Boot more than a year ago. Finally I have the time and inspiration for this. So prepare yourself for 10 – 15 minutes of high quality Spring tutorial. I’m going to demonstrate Spring Boot basics with Gradle and embedded Tomcat. I use Intellij IDEA instead of Eclipse but this shouldn’t be a problem for those of you who are used to Eclipse.

Introduction to Spring Boot

What’s my goal? I want to develop something very similar to one of my previous tutorials about Spring and Java configurations. It’s a good exercise to compare two different approaches for Spring development.
No doubt, most of you know what is the main aim of Spring Boot. For the rest of readers I want to say that Spring Boot makes developers happier because it takes care of configurations while developers can focus on code production. For more details read official reference.

Gradle build file

Spring-Boot-Project-256x300

For managing dependencies and build of the project I use Gradle. Here is how build.gradle file looks:

buildscript {
    repositories {
        //Required repos
        mavenCentral()
        maven { url "http://repo.spring.io/snapshot" }
        maven { url "http://repo.spring.io/milestone" }
    }
    dependencies {
        //Required dependency for spring-boot plugin
        classpath 'org.springframework.boot:spring-boot-gradle-plugin:1.1.2.BUILD-SNAPSHOT'
    }
}

apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'spring-boot'

war {
    baseName = 'companies'
    version =  '0.1'
}

repositories {
    mavenCentral()
    maven { url "http://repo.spring.io/snapshot" }
    maven { url "http://repo.spring.io/milestone" }
}

dependencies {
    compile 'org.springframework.boot:spring-boot-starter-web'
    //Required dependency for JSP
    providedRuntime 'org.apache.tomcat.embed:tomcat-embed-jasper'
}

If you are new to Gradle, I recommend you to read about it somewhere else, e.g. on official site. It’s really nice and practical tool. It can do everything what Maven do, but without XML!

Spring Boot initialization

Now we can set up Spring Boot on java code level.

package com.companies;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan
@EnableAutoConfiguration
public class CompanyApplication {

    public static void main(String[] args) {
        SpringApplication.run(CompanyApplication.class, args);
    }

}

That’s it, now you can start developing your business logic. Just kidding, we need to put some extra configs related to view resolving.

package com.companies.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter{

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("WEB-INF/pages/");
        resolver.setSuffix(".jsp");
        return resolver;
    }

}

After you have created the class published above, you can go ahead with controller development.

Controller & View

package com.companies.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloWorldController {

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public ModelAndView hello() {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("hello");
        
        String str = "Hello World!";
        mav.addObject("message", str);

        return mav;
    }

}

And corresponding view hello.jsp for the controller:

<html>
<head>
    <title>Hello world page</title>
</head>
<body>
    <h1>${message}</h1>
</body>
</html>

I hope it wan’t hard to repeat all these steps.

Run Spring Boot application

The last thing we have to do in this tutorial is launch of the application. Hence I use Gradle, and in our build.gradle file I specified that the application needs to be packaged as WAR file – I need to run build and run war file.
Here is how it looks like in IDEA:

spring-boot-run-300x134

Result you can see here: localhost:8080/hello

Reference: Spring Boot: Fast MVC start from our JCG partner Alexey Zvolinskiy at the Fruzenshtein’s notes blog.
Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

Leave a Reply


three − = 2



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books