Mathias Hauser

My opinions and thoughts on various things and experiences of software development

Bootstrap an application with Spring Boot – Part1 Command-line

Spring Boot is a new piece of technology with the aim to reduce the configuration overhead and easier project bootstrap. There are many little examples out there which describe how to use it, but there is in many cases something that you don’t want or a configuration parameter you need, but not mentioned in a specific tutorial. I try to give you a good starting point for you application plus additional references to additional informations you might need for your setup.

Command-line application with Spring Boot

Most Spring Boot examples are web applications. This is ok because many new applications are web based, but its not optimal in each situation. I personally prefer to start with as little new as possible. My experience is that solving problems with two new things cost more time than solving one after another. So I decided to start things off with a really simple command-line application which allows inserting a word with a specific text to the database.

I recommend downloading the source of this example before you start. Link to the repository blog_springBoot-commandLine direct link to the source zip source-zip

Four key points of the configuration

  1. Build- and Dependencymanagement -> build.gradle -> in the project root
  2. Application configuration -> Application.java -> anywhere in your package structure in this case mh.dev.blog (src/main/java)
  3. Property configuration -> application.yml -> src/main/resources
  4. Logging configuration -> logback.xml -> src/main/resources

Build- and Dependencymanagement -> build.gradle

This file is located in the root of the project. The majority of the file is a standard gradle script. Only the dependencies are specific for this Spring Boot project. I also include Apache Commons Lang and Google Guava into my projects even if I might not need them.

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'

version = '1.0'
group = 'mh.dev.blog'
description = 'bootstrap-spring-boot'

project.ext {
	springBootVersion = '1.0.0.RC1'
}

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

dependencies {
    compile("org.springframework.boot:spring-boot-starter:$springBootVersion")
    compile("org.springframework.boot:spring-boot-starter-data-jpa:$springBootVersion")
    compile("org.apache.commons:commons-lang3:3.2.1")
    compile("com.google.guava:guava:16.0.1")
    compile("org.yaml:snakeyaml:1.13")
    compile("mysql:mysql-connector-java:5.1.28")
}

task wrapper(type: Wrapper) {
    gradleVersion = '1.10'
}

Dependencies

  • spring-boot-starter – responsible for the Spring Boot magic
  • spring-boot-starter-data-jpa – integrates Spring Data JPA into the environment
  • snakeyaml – library for a special property configuration syntax -> application.yml

Wrapper task

The wrapper task is a nice extra from gradle it allows to create files which can be added to the repository. One of these files is graldew.bat it allows to download the gradle distribution on demand as long as JAVA_HOME is set in the environment variables. More details see gradle wrapper documentation

How to create Eclipse / IntelliJ project with the source-zip

Navigate with the command line to the folder where build.gradle is located and type the following

  • Eclipse -> windows: gradlew eclipse or unix: ./gradlew eclipse
  • IntelliJ -> windows: gradlew idea or unix: ./gradlew idea

From this command generated project can now be opened with the respective IDE.

Appication configuration -> Application.java

The following class is the main configuration of your application. The “@EnableAutoConfiguration” annotation is the key part which configures the application itself based on dependencies on the classpath. Don’t think to much about how this works, accept that it reduces the amount of configurations you have to do on your own. The other two annotations should be self-explanatory. ComponentScan activates the scanning for classes which should be added to the application context and EnableJpaRepositories is responsible for the magic of Spring Data JPA.

package mh.dev.blog;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@ComponentScan
@EnableJpaRepositories
@EnableAutoConfiguration
public class Application {

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

}

Further configuration possibilities

You might want to use async methods or scheduling. Annotations for that case are @EnableAsync and @EnableScheduling. Or you might want something else just try @Enable and use the autocompletion of your IDE to activate specific features.

Property configuration -> application.yml

Well Spring Boot reduces the amount of required configuration, but there are some things which can’t be automatically configured. These properties are located in a specific configuration file. New with Spring Boot is the possibility to use YAML as syntax for this file.
In the file itself is a reference to a page with a lot of existing properties.

Database configuration

Important in our case is the database configuration. You can change it for your local environment to be suitable for you environment. I’ve decided to use the update strategy.

  • Databasename: blog
  • Username: root
  • Passowrd: root
  • ddl-auto: update/create/create-drop/validate
## based on example application.yml -> https://github.com/spring-projects/spring-boot/blob/6b83e0ad5de5f127cad5b12ab1738923c4a58a9f/docs/application.yml

spring:
  application.name: CommandLineRunner
  
  datasource:
    driverClassName: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/blog
    username: root
    password: root
  
  jpa:
     show-sql: true
     hibernate:
       ddl-auto: update

Command-line runner

The HelloWorldController shown in the next code segment is the application itself. This example contains two important things.

  1. @Controller – allows the class to detected by Spring -> @ComponentScan
  2. implements CommandLineRunner – an interface with a run method which is automatically invoked by Spring

I don’t explain the Word, WordRepository, WordService class in this blog entry. You can take a look at it in the code but they don’t contain something Spring Boot specific.

package mh.dev.blog.controller;

import java.util.Scanner;

import mh.dev.blog.model.Word;
import mh.dev.blog.service.WordService;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Controller;

@Controller
public class HelloController implements CommandLineRunner {

	@Autowired
	private WordService wordService;

	private Logger log = Logger.getLogger(HelloController.class);

	@Override
	public void run(String... args) throws Exception {
		try (Scanner scanner = new Scanner(System.in)) {
			log.info("Enter text for a new word");
			String text = scanner.nextLine();
			if (wordService.byText(text) == null) {
				Word word = wordService.createWord(text);
				log.info(String.format("Word with text %s and id %d created!", word.getText(), word.getId()));

			} else {
				log.error(String.format("Word with text %s does already exist!", text));
			}
			log.info("Restart the application to creat additional words");
		}
	}
}

Multiple Command-line runners

You can define multiple command-line runners, but the execution is per default not parallel.

Logging with logback

Spring Boot supports logging configuration with Logback out of the box. The only thing you need to do is to include the base configuration from Spring Boot.

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
	<include resource="org/springframework/boot/logging/logback/base.xml" />
	<logger name="org.springframework.web" level="DEBUG" />
	<logger name="mh.dev.blog" level="DEBUG" />
</configuration>

Further reading and references

Plan for my next entry

My next entry will be part 2 of this blog entry with the focus on a web based Spring Boot application. I’m not sure which web technology I should use for this maybe AngularJS?
The entry is finally realesed Bootstrap an application with Spring Boot – Part2 Webapplication

Advertisements

11 responses to “Bootstrap an application with Spring Boot – Part1 Command-line

  1. Steve Gelman October 5, 2014 at 10:35 pm

    Thank you. This is a nice starting point. However, I had to add my own CRUDRepository class. I did not see any reference to needing to do this, though it could be my error.

    package mh.dev.blog.repository;
    import org.springframework.data.repository.CrudRepository;
    import mh.dev.blog.model.Word;
    public interface WordRepository extends CrudRepository {
    Word findByText(String text);
    }

  2. mhdevelopment October 5, 2014 at 10:45 pm

    Sorry, seems that i forgot to add this file to the commit. Its now added.
    I also fixed some special characters, wordpress has converted them for any reason at a later point.
    Thanks for the info 🙂

  3. Amit December 17, 2014 at 2:36 pm

    Nice article to start. One question – how can I upgrade spring-boot version? To be specific – What task do I execute in gradle after changing the spring boot version in build.gradle file ?

  4. mhdevelopment December 17, 2014 at 4:33 pm

    In that case its just updating the entry
    project.ext {
    springBootVersion = ‘1.0.0.RC1’
    }
    to the version you prefer. The current version is 1.2.0.RELEASE.
    But keep in mind that it might be necessary to refresh the dependencies in Intellij/Eclipse

  5. mhdevelopment December 18, 2014 at 7:01 am

    I would rely on the gradle plugin of Intellij, but that depends on the version of Intellij your using. The following approach works for at least 13 and 14.
    1. Import Project
    2. Select the build.gradle file
    3. Intellij does now import the whole project as a gradle project for you.
    4. Open the gradle view on the right side and click the “Refresh all Gradle projects” button, after changing dependencies. (Its ~a blue arrow cycle)

    • Amit December 18, 2014 at 7:06 am

      Great. That seems to working. Thanks for the quick reply. I wonder there should be a gradle task for doing the same.

      • mhdevelopment December 18, 2014 at 8:13 am

        Of course you can reexecute gradlew idea, but I told you the way I do it. Theres no point in switching to the console, for something you can do with Intellij with just a click on a single button.

    • Amit December 18, 2014 at 10:00 am

      For some reason spring dependencies are not getting downloaded when I refresh the gradle project. I updated the gradle file as I pasted here – https://paste.ee/p/TsZY7 and refreshed. The newly added oracle jar dependency was fetched and added in idea’s dependency list but
      none of the spring jars were downloaded.

      Even executing “gradlew idea” doesn’t download the spring dependencies.

      Any guesses on what could be wrong?

  6. priya bapte March 11, 2015 at 12:48 pm

    I want to restart a spring boot app. like when user hit where url /restart the application should restart. any idea about this ?

    Thanks in advance.
    -Priya

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: