You are here
Home > java >

Spring Boot Features

Spring Boot FeatuesAfter knowing about ‘What is Spring Boot?‘ in detail in a separate article, it’s time to talk about the features of Spring Boot. Needless to say, Spring Boot is full of features, that’s why it is being used in the majority of Java projects now-a-days. In this article, we are going to discuss Spring Boot Features in detail.

If you are attending any interview of Java/Spring Boot, there are high chances that you may be asked to tell some important features of Spring Boot.

Spring-Boot comes with a lot of handy features that make the developer’s life easier. Below are some of the important Spring Boot Features.

CommandLineRunner

CommandLineRunner is a very handy Spring Boot Features while testing a functionality just like the thread’s run() method in Core Java. If we want to run some specific code once the Spring Boot Application has started, we can implement the CommandLineRunner interface. This interface provides a single run() method which is called just before SpringApplication.run() completes. Similarly, we have one more interface ApplicationRunner that we can also use. For example, the following code demonstrates the use of CommandLineRunner with the run() method.

@Component 
public class MyCommandLineRunner implements CommandLineRunner {
    
    @Override 
    public void run(String... args) {
       // code that you want to run only once 
    } 
}

If there are several CommandLineRunner or ApplicationRunner beans defined that must be called in a specific order, you can additionally use the @Order annotation or implement the org.springframework.core.Ordered interface.

Note: Don’t forget to apply the @Component annotation on the top of your custom runner class, otherwise you will not see any result on the console. Many developers make this mistake, especially beginners in this field.

Externalized Configuration

Spring Boot offers you to externalize your configuration so that you can work with the same application code in different environments. You can use a variety of external configuration sources, including Java properties files, YAML files, environment variables, and command-line arguments. However, the two formats : ‘.properties’ & ‘.yml’ are the most popular in Spring Boot. Moreover, it is recommended to stick with one format for your entire application. If you have configuration files with both .properties and .yml format in the same location, .properties takes precedence.

YAML

YAML is a superset of JSON and, as such, is a convenient format for specifying hierarchical configuration data. If you have SnaleYAML library on your class path, Spring Boot automatically supports YAML as an alternative to .properties file. However, If you use “Starters”, SnakeYAML automatically comes with spring-boot-starter. YAML format files takes extension as ‘.yml’.

Mapping YAML to Properties

As aforementioned, YAML files are known for their hierarchical structure. Here will will take an example of YAML file in order to know how it looks. Further, we will convert it to a properties file. For example, consider the following ‘.yml’ file.

environments: 
  prod: 
    url: https://prod.example.com
    name: Production Setup
    host: 10.10.10.40 
  dev: 
    url: https://dev.example.com 
    name: Development Setup
    host: 10.10.10.30

it’s equivalent ‘.properties’ file will look like below:

environments.prod.url=https://prod.example.com 
environments.prod.name=Production Setup
environments.prod.host=10.10.10.40
environments.dev.url=https://dev.example.com
environments.dev.name=Development Setup 
environments.dev.host=10.10.10.30

Furthermore, let’s take an example of properties with index. For example, consider the following ‘.yml’ file.

prod: 
  servers:
  - prod1.example.com
  - prod2.example.com
dev: 
 servers:
 - dev1.example.com
 - dev2.example.com

it’s equivalent ‘.properties’ file will look like :

prod.servers[0]=prod1.example.com
prod.servers[1]=prod2.example.com
dev.servers[0]=dev1.example.com
dev.servers[1]=dev2.example.com

Hence, Properties that use the [index] notation can be bound to Java List or Set objects easily. However, YAML files cannot be loaded by using the @PropertySource or @TestPropertySource annotations. So, in that case, you need to use a ‘.properties’ file. Moreover, Spring Framework provides two convenient classes that we can use to load YAML documents. The YamlPropertiesFactoryBean loads YAML as Properties and the YamlMapFactoryBean loads YAML as a Map. We can also use the YamlPropertySourceLoader class if we want to load YAML as a Spring PropertySource.

Profiles

Spring Profiles offer a way to separate out parts of your application configuration and make it be available only in particular environments. We can mark @Profile on top of any class annotated with @Component, @Configuration or @ConfigurationProperties to limit when it is loaded. For example, below code demonstrates the concept.

@Profile("production") 
@Configuration 
public class ProductionConfig { 
        // ... 
}

Moreover, we can use a ‘spring.profiles.active’ Environment property to describe which profiles are active. For example, we could include it in our ‘application.properties’, as shown in the following example:

spring.profiles.active=prod

Profile Groups

Sometimes we could need to create multiple profiles to separate artifacts. For example, we might have db profiles and security profiles that we use to enable database and security features separately. In order to help with this, Spring Boot offers us to define profile groups. A profile group allows us to define a logical name for a related group of profiles. For example, we can create a production group that consists of our proddb and prodsecurity profiles. For instance, we will need below entry in our application.properties file.

spring.profiles.group.production[0]=proddb 
spring.profiles.group.production[1]=prodsecurity

Consequently, our application can now be started using ‘–spring.profiles.active=production‘ to activate the production, proddb and prodsecurity profiles in one hit.

JSON Support

Spring Boot provides integration with three JSON mapping libraries:

1) Jackson
2) Gson
3) JSON-B

Jackson is the preferred and default library. Auto-configuration for Jackson is provided and Jackson is part of starter-json. However, when Jackson is on the classpath an ObjectMapper bean is automatically configured. Similarly, when Gson is on the classpath a Gson bean is automatically configured. Several ‘spring.gson.*‘ configuration properties are provided for customizing the configuratioAlso, when the JSON-B API and an implementation are on the classpath a Jsonb bean will be automatically configured.

Web Application Development Support

The Spring Web MVC framework (often referred to as “Spring MVC”) is a rich “model view controller” web framework. Spring Boot is very suitable for such kind of web application development. Undoubtedly, we can take advantage of embedded servers like Tomcat, Jetty, Undertow. In order to develop a web application, we can use the ‘spring-boot-starter-web‘ Starter to get up and running a web application quickly. Moreover, in order to build reactive web applications, we can use the ‘spring-boot-starter-webflux‘ starter.

If you are new to a Spring Boot web application, you can follow the instructions for “Hello World!” example given in the spring.io documentation section. There are also several guides that cover Spring MVC available at spring.io/guides.

Support for Template Engines

Spring MVC supports a variety of templating technologies, including Thymeleaf, FreeMarker, and JSPs. Furthermore, many other templating engines include their own Spring MVC integrations. However, Spring Boot offers auto-configuration support for the following templating engines:

1) Thymeleaf
2) FreeMarker
3) Groovy
4) Mustache

Although, Thymeleaf is the most popular template Engine that we often use in our SpringBoot Projects.

Error Handling Support

By default, Spring Boot comes up with an ‘/error’ mapping that handles all errors in a practical way, and it is registered as a “global” error page in the servlet container. For machine clients, it produces a JSON response with details of the error, the HTTP status, and the exception message. For browser clients, there is a “whitelabel” error view that renders the same data in HTML format. However, in order to customize it, we can add a View page that resolves to error with a meaningful message accordingly.

In order to replace the default behavior completely, you can implement ErrorController and register a bean definition of that type or add a bean of type ErrorAttributes to use the existing mechanism but replace the contents. For further details on how to develop custom error handling, including all possibilities, kindly visit ‘How to handle Errors & Exceptions in SpringBoot?‘.

The Spring WebFlux Framework

Spring WebFlux is the new reactive web framework introduced in Spring Framework 5.0. Unlike Spring MVC, it does not require the Servlet API. Moreover, It is fully asynchronous and non-blocking, and implements the Reactive Streams specification through the Reactor project.

In fact, Spring WebFlux comes in two flavors: functional and annotation-based. The annotation-based one is quite close to the Spring MVC model. Furthermore, in order to learn on how to work with Spring Webflux, kindly visit our article on ‘How To Develop A Reactive CRUD REST API With Spring WebFlux?‘.

Spring Boot provides support for the following embedded reactive web servers: Reactor Netty, Tomcat, Jetty, and Undertow. However, most developers use the appropriate “Starter” in order to obtain a fully configured instance. By default, the embedded server listens for HTTP requests on port 8080.

JSP Limitations

When running a Spring Boot application that uses an embedded servlet container (and is packaged as an executable archive), there are some limitations in the JSP support.

1) With Tomcat and Jetty servers, it should work if you use war packaging. However, an executable war will work when launched with java -jar, and will also be deployable to any standard container. JSPs are not supported when using an executable jar.
2) Undertow does not support JSPs.
3) Creating a custom error.jsp page does not override the default view for error handling. Further, Custom error pages should be used instead.

In-built Security Feature

By default, Spring Boot offers minimum level security on a Web Application, if Spring Security in on the class path. The basic security features that we get by default in a web application are:

1) A UserDetailsService (or ReactiveUserDetailsService in case of a WebFlux application) bean with in-memory store and a single user with a generated password (see SecurityProperties.User for the properties of the user).
2) Form-based login or HTTP Basic security (depending on the Accept header in the request) for the entire application (including actuator endpoints if actuator is on the classpath).
3) A DefaultAuthenticationEventPublisher for publishing authentication events.

Furthermore, If you want to learn more on Spring Boot Security, kindly visit our all articles on ‘SpringBoot Security‘.

Support for SQL Databases

The Spring Framework offers large-scale support for working with SQL databases, from direct JDBC access using JdbcTemplate to complete “object relational mapping” technologies such as Hibernate. Moreover, Spring Data further offers an additional level of functionality such as creating Repository implementations directly from interfaces and using conventions to generate queries from our method names.

On the other hand, it is often favorable to develop applications by using an in-memory embedded database. Noticeably, in-memory databases do not provide permanent storage. We need to populate our database when application starts and be prepared to get our data lost when application ends.

Spring Boot can auto-configure embedded databases such as H2HSQL, and Derby. Moreover, we don’t need to provide any connection URLs. We only need to specify a build dependency to the embedded database that we want to use.

JdbcTemplate

JdbcTemplate and NamedParameterJdbcTemplate are the classes of Spring that are auto-configured. In fact, we can directly use them in our beans via @Autowired.

JPA and Spring Data JPA

The JPA(Java Persistence API) is a standard technology that lets us “map” objects to relational databases. Moreover, the ‘starter-data-jpa’ dependency provides a quick way to get started. Furthermore, you can follow the “Accessing Data with JPA” guide from spring.io and read the Spring Data JPA and Hibernate reference documentation.

Spring Data JDBC

Spring Data provides repository support for JDBC and will automatically generate SQL for the methods on CrudRepository. However, For more advanced queries, a @Query annotation is provided. Furthermore, Spring Boot will auto-configure Spring Data’s JDBC repositories when the required dependencies are on the classpath. We can add to our project by providing a single dependency as ‘starter-data-jdbc’. Moreover, for complete details of Spring Data JDBC, please refer to the reference documentation.

R2DBC

In fact, the Reactive Relational Database Connectivity (R2DBC) project brings reactive programming APIs to relational databases. R2DBC’s ‘io.r2dbc.spi.Connection’ offers a standard method of working with non-blocking database connections. Moreover, connections are provided via a ConnectionFactory, similar to a DataSource with jdbc. ConnectionFactory configuration is controlled by external configuration properties in ‘spring.r2dbc.*’. For example, you may declare the following section in application.properties as below:

spring.r2dbc.url=r2dbc:postgresql://localhost/test
spring.r2dbc.username=dbuser
spring.r2dbc.password=dbpass

Support for NoSQL Databases

Spring Data also offers some additional projects that helps us access a variety of NoSQL databases such as MongoDB, Neo4J, ElasticSearch, Redis, GemFire or Geode, Cassandra, Couchbase, LDAP. In fact, Spring Boot provides auto-configuration for Redis, MongoDB, Neo4j, Solr, Elasticsearch, Cassandra, Couchbase, LDAP and InfluxDB. However, we can make use of the other projects, but we must configure them ourself. Moreover, refer to the appropriate reference documentation available at spring.io/projects/spring-data.

MongoDB

MongoDB is the most popular NoSQL database. It is an open-source NoSQL document database. However, MongoDB uses a JSON-like schema instead of traditional table-based relational data. Spring Boot offers several convenient ways for working with MongoDB, including the ‘starter-data-mongodb’ and ‘starter-data-mongodb-reactive’ “Starters”. Furthermore, if you want to have a good hold on MongoDB with Spring Boot, kindly visit our series of articles on ‘SpringBoot Projects with MongoDB‘.

Support for Caching

Spring Boot auto-configures the cache infrastructure as long as caching support is enabled via the @EnableCaching annotation. In a nutshell, in order to add caching to an operation of your service add the relevant annotation to its method. For example, below code demonstrates the concept.

@Component 
public class MyMathService {
    @Cacheable("piDecimals") 
    public int computePiDecimal(int precision) {
           ... 
    }
}

This example demonstrates the use of caching on a potentially costly operation. However, before invoking computePiDecimal, the abstraction looks for an entry in the piDecimals cache that matches the i argument. If an entry is found, the content in the cache is immediately returned to the caller, and the method is not invoked. Otherwise, the method is invoked, and the cache is updated before returning the value.

Messaging Support

The Spring Framework provides large-scale support for integrating with messaging systems, from simplified use of the JMS API using JmsTemplate. However, JMS API is a complete infrastructure to receive messages asynchronously. Spring AMQP provides a similar feature set for the Advanced Message Queuing Protocol. Spring Boot also provides auto-configuration options for RabbitTemplate and RabbitMQ. Moreover, Spring Boot also has support for Apache Kafka.

Calling REST Services with RestTemplate

When we need to call remote REST services from our application, we can use RestTemplate class provided by Spring Framework. Since instances of RestTemplate often need to be customized before being used, Spring Boot doesn’t offer any single auto-configured RestTemplate bean. It does, however, auto-configure a RestTemplateBuilder, which can be used to create RestTemplate instances when needed. Furthermore, you can go through the article on ‘How to write REST Consumer API ? : The RestTemplate‘.

Calling REST Services with WebClient

When we are into Reactive Programming, we can use WebClient instead of RestTemplate. In comparision to RestTemplate, the WebClient has a more functional feel and is fully reactive. In a nutshell, we can also choose to use WebClient to call remote REST services, If wehave Spring WebFlux on our classpath. Furthermore, you can go through the article on ‘How to develop a Reactive Client Application with WebClient ?‘.

Sending Email

The Spring Framework offers an abstraction for sending email by using the JavaMailSender interface. However, Spring Boot further simplified the process by providing auto-configuration for it as well as a starter module ‘starter-mail’. Furthermore, you can visit the reference documentation for a detailed explanation of how you can use JavaMailSender.

Spring Integration Support

Spring Boot provides variety of convenient ways to work with Spring Integration. It also includes ‘starter-integration’ “Starter” for this purpose. Moreover, Spring Integration provides abstractions over messaging and also other transports such as HTTP, TCP, and others. If Spring Integration is available on your classpath, it is initialized through the @EnableIntegration annotation.

Spring Boot also configures some features that are triggered by the presence of additional Spring Integration modules. For example, If ‘spring-integration-jmx’ is also on the classpath, message processing statistics are published over JMX. Similarly, If ‘spring-integration-jdbc’ is available, the default database schema can be created on startup.

Testing Support

Spring Boot offers a number of utilities and annotations to help while testing your application. However, Test support is provided by two modules: ‘spring-boot-test’ and ‘spring-boot-test-autoconfigure’. ‘spring-boot-test’ contains core items, whereas ‘spring-boot-test-autoconfigure’ supports auto-configuration for tests.

Most developers use the ‘spring-boot-starter-test’ “Starter”, which imports both SpringBoot test modules as well as JUnit Jupiter, AssertJ, Hamcrest, and a number of other useful libraries in order to autoconfigure them.

Kotlin Support

Spring Boot provides Kotlin support by leveraging the support in other Spring projects such as Spring Framework, Spring Data, and Reactor. Kotlin is nothing but a statically-typed language targeting the JVM (and other platforms) which allows writing concise and elegant code while providing interoperability with existing libraries written in Java. Further, the easiest way to start with Spring Boot and Kotlin is to follow this comprehensive tutorial. Moreover, you can create new Kotlin projects via start.spring.io.

Container Images

Obviously, It is easily possible to package a Spring Boot fat jar as a docker image. However, there are various pitfalls to copying and running the fat jar as is in the docker image. In order to make it easier to create optimized Docker images, Spring Boot supports adding a layer index file to the jar. Moreover, It provides a list of layers and the parts of the jar that should be contained within them.

Furthermore, Spring Boot applications can be containerized using Dockerfiles, or by using Cloud Native Buildpacks to create docker compatible container images that you can run anywhere. While it is possible to convert a Spring Boot fat jar into a docker image with just a few lines in the Dockerfile. Furthermore, you can go through the article on ‘How to deploy a SpringBoot application in Docker?

Although, Dockerfiles are just one way to build docker images. Another way to build docker images is directly from your Maven or Gradle plugin, using buildpacks. If you’ve ever used an application platform such as Cloud Foundry or Heroku then you’ve probably used a buildpack. Further, you can refer to the individual plugin documentation on how to use buildpacks with Maven and Gradle.

What are the options to deploy a Spring Boot Application?

Undoubtedly, there are multiple options to deploy your Spring Boot application to the cloud.

1) Cloud Foundary
2) Kubernetes
3) Heroku
4) OpenShift
5) AWS (Amazon Web Services)
6) Boxfuse and AWS
7) Google Cloud

Conclusion

In this article we have covered all the conceptual part of ‘Spring Boot Features’, finally, you should have a general idea on Spring Boot Project Features. Similarly, we expect from you to further extend these concepts, as per your requirement. Also try to implement them in your project accordingly. Moreover, we will update the article time to time if it becomes important to do so. Additionally, don’t hesitate to put your comments below.

close

Leave a Reply

Top