Skip to main content

Development

Developing Spring Boot Application and Learning Core Features

Introduction of spring boot

Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can “just run”. We just need Spring platform and third-party libraries so you can get started with minimum fuss. Most Spring Boot applications need very little Spring configuration. You can use Spring Boot to create Java applications that can be started using java -jar or more traditional war deployments.

System Requirements

By default 1.5.3.RELEASE requires java 7 and spring framework 4.3.8 or above. And explicit build support is provided for Maven (3.2+), and Gradle2 (2.9 or later). Spring boot support following embedded servlet containers, such as tomcat 8, tomcat 7, jetty 9, jetty 8 and Undertow 1.3.

Developing your first spring boot application

Before we begin, please check that you have valid versions of Java and Maven installed.

Let’s develop a simple “Hello World!” to get familiar with spring boot’s key features. We will use maven to build this project since most IDEs support it.

  1. Creating the POM

We should create a pom.xml file first, then it will be used to build your project.

  1. Add classpath dependencies

Spring Boot provides a number of “Starters” that make easy to add jars to your classpath. Our sample application has already used spring-boot-starter-parent in the parent section of the POM. The spring-boot-starter-parent is a special starter that provides useful Maven defaults. It also provides a dependency-management section so that you can omit version tags for “blessed” dependencies.

Spring Boot also provides an optional Maven plugin to create executable jars. So we just add below to pom.xml, we can get an executable jar as we expected.

  1. Writing the code

Locating the main application class

Before we create the main application class, we should make it clear that where the class should be located. Here is a typical layout:

We generally recommend that you locate your main application class in a root package above other classes. The @EnableAutoConfiguration annotation is often placed on your main class, and it implicitly defines a base “search package” for certain items.

Example code

Application class:

Controller class:

Result:

@SpringBootApplication is a convenience annotation that adds all of the following:

@Configuration: tags the class as a source of bean definitions for the application context.

@EnableAutoConfiguration: this annotation tells Spring Boot to “guess” how you will want to configure Spring, based on the jar dependencies that you have added. Since spring-boot-starter-web added Tomcat and Spring MVC, the auto-configuration will assume that you are developing a web application and setup Spring accordingly.

@ComponentScan: tells Spring to look for other components, configurations, and services in the current package, allowing it to find the controllers.

“main” method: this is a standard method that follows the Java convention for an application entry point. Our main method delegates to Spring Boot’s SpringApplication class by calling run. SpringApplication will bootstrap our application, starting Spring which will in turn start the auto-configured Tomcat web server. We need to pass Application.class as an argument to the run method to tell SpringApplication which is the primary Spring component. The args array is also passed through to expose any command-line arguments.

creating an executable jar

You can run mvn package from the command line or run as maven build in eclipse to get an executable jar.

If you look in the target directory you should see springboot-demo-0.0.1-SNAPSHOT.jar. Then you can run this application in command line.

Learn about spring boot features

  1. SpringApplication

The SpringApplication class provides a convenient way to bootstrap a spring application that will be started from a main method. In many situations you can just delegate to the static SpringApplication.run() method.

Customizing the Banner

Add banner.txt file to your classpath, the context which is printed on startup will be change. Inside your banner.txt file you can use some of the following placeholders:

${application.version}

${spring-boot.version}

${spring-boot.formatted-version}

You can also use the spring.main.banner-mode property to determine if the banner has to be printed on console, using the configured logger or not at all.

Customizing SpringApplication:

  1. Externalized Configuration

Spring boot allows you to externalize your configuration so you can work with the same application code in different environments. You can use properties files, YAML files, environment variables and command-line arguments to externalize configuration. Property values can be injected directly into your beans using the @Value annotation.

Application property files

application.properties

SpringApplication will load properties from application.properties files in the following locations and add them to the Spring Environment:

A /config subdirectory of the current directory

The current directory

A classpath /config package

The classpath root

The list is ordered by precedence (properties defined in locations higher in the list override those defined in lower locations).

application-{profile}.properties

In addition to application.properties files, profile-specific properties can also be defined using the naming convention application-{profile}.properties (such as application-dev.properties). It loaded from the same locations as standard application.properties, with profile-specific files always overriding the non-specific ones.

Placeholders in properties

YAML files

YAML is superset of JSON, and as such is very convenient format for specify configuration data. The SpringApplication class will automatically support YAML.

There are two classes can be used to load YAML documents. YamlPropertiesFactoryBean will load YAML as Properties and the YamlMapFactoryBean will load YAML as a Map.

There are two methods to read properties from application file or YAML file.

a.You can use the @Value annotation to inject the property values into your beans.

b.Using the @Value(“${property}”) annotation to inject configuration properties can sometimes be cumbersome. Spring Boot provides an alternative method of working with properties that allows strongly typed beans to govern and validate the configuration of your application. So let us create a class such as ConfigBean.java, we should use @ConfigurationProperties (prefix = “application”) to indicate which one will be read. You also need to list the properties classes to register in the @EnableConfigurationProperties annotation.

application.yml

YAMLConfig.java

YAMLConfigController.java

  1. Profiles

Spring profiles provide a way to segregate parts of your application configuration and make it only available in certain environments. Any @Component or @Configuration can be marked with @Profile to limit when it is loaded.

In the normal spring way, you can use a spring.profiles.active Environment property to specify which profiles are active. You can add spring.profiles.active=dev in your application.properties, then the application-dev.properties will be activated.

  1. logging

Spring Boot uses Commons Logging for all internal logging, but leaves the underlying log implementation open. Default configurations are provided for Java Util Logging, Log4J2 and Logback. In each case loggers are pre-configured to use console output with optional file output also available.

File output

If you want to write log files in addition to the console output you need to set a logging.file or logging.path property.

Log Levels

You can set the logger levels in spring environment, for example in application.properties:

logging.level.root=WARN

logging.level.org.springframework.web=DEBUG

logging.level.org.hibernate=ERROR

Custom log configuration

Firstly, you can include the appropriate libraries on the classpath to activated the logging systems.

Secondly, providing a suitable configuration file in the root of the classpath (such as if using Log4j system, you should add log4j.properties or log4j.xml in the classpath).

  1. Developing web applications

Spring Boot is well suited for web application development. You can easily create a self-contained HTTP server using embedded Tomcat. Most web applications will use the spring-boot-starter-web module to get up and running quickly.

As well as REST web services, you can also use Spring MVC to serve dynamic HTML content. Spring MVC supports a variety of templating technologies including Thymeleaf, FreeMarker and JSPs. Spring Boot includes auto-configuration support for these templating engines. You just need to add the dependency in pom.xml, this is an example to support thymeleaf template.

When you’re using templating engine with the default configuration, your templates will be picked up automatically from src/main/resources/templates.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Categories
Follow Us