Spring-Boot / Groovy / MVC “Hello World” example
The complete project can be found here:
https://github.com/mtrojahn/spring-boot-groovy-mvc-simple
This is yet another very basic example. This time I’ll show how to create get a Web-MVC Spring-Boot project started. You will notice I take the no-XML approach and I’ll try to keep my examples as XML-free as they can be because it’s hard to find fresh documentation about it on the Web.
So, let me start with the build.gradle file:
group 'com.mtrojahn' version '1.0-SNAPSHOT' buildscript { repositories { mavenCentral() } dependencies { classpath "org.springframework.boot:spring-boot-gradle-plugin:1.3.0.RELEASE" } } apply plugin: 'groovy' apply plugin: 'spring-boot' repositories { mavenCentral() } sourceCompatibility = 1.8 targetCompatibility = 1.8 dependencies { compile "org.springframework.boot:spring-boot-starter-web" compile 'org.codehaus.groovy:groovy-all' testCompile "junit:junit" } bootRun { addResources = true }
As you can see, no big changes from my previous example. Basically all you have to do is change spring-boot-starter to spring-boot-starter-web.
Ok, now let’s have a look on the our main class:
package com.mtrojahn package com.mtrojahn import org.springframework.boot.Banner import org.springframework.boot.autoconfigure.EnableAutoConfiguration import org.springframework.boot.builder.SpringApplicationBuilder import org.springframework.context.annotation.ComponentScan @EnableAutoConfiguration @ComponentScan(basePackages = "com.mtrojahn.mvc") class Application { static main(args) { new SpringApplicationBuilder() .sources(Application.class) .bannerMode(Banner.Mode.OFF) .run() } }
I didn’t use @SpringBootApplication this time because I wanted to add a little configuration to it:
The @EnableAutoConfiguration annotation tells Spring-Boot to configure beans based on what it sees on my classpath. It will see spring-webmvc and flag this as a web application. Spring-Boot will provide you an embedded Tomcat server that will listen on port 8080 as default, among other things.
@ComponentScan configures the scanning for @Configuration classes and in this case it’s telling Spring to scan the package that holds my MVC Controller.
Here’s the MVC Controller:
package com.mtrojahn.mvc import org.springframework.stereotype.Controller import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.ResponseBody @Controller class MvcController { @RequestMapping(value = "/") def @ResponseBody hello() { return "Hello World!" } }
This @Controller will just show the traditional “Hello World!” message when you point your browser to “http://localhost:8080/”. The @RequestMapping annotation is responsible for mapping the URL “/” to the method “hello()” which just returns a string.
That’s it, folks.