What Are the Differences Between Spring and Spring Boot?
What is Spring?
The Spring framework provides comprehensive infrastructure support for developing Java applications.
It’s packed with some nice features like Dependency Injection and out of the box modules like:
- Spring JDBC
- Spring MVC
- Spring Security
- Spring AOP
- Spring ORM
- Spring TestThese modules can drastically reduce the development time of an application.For example, in the early days of Java web development, we needed to write a lot of boilerplate code to insert a record into a data source. But by using the JDBCTemplate of the Spring JDBC module we can reduce it to a few lines of code with only a few configurations.’ What is Spring Boot?Spring Boot is basically an extension of the Spring framework which eliminated the boilerplate configurations required for setting up a Spring application.It takes an opinionated view of the Spring platform which paved the way for a faster and more efficient development eco-system.Here are just a few of the features in Spring Boot:
- Opinionated ‘starter’ dependencies to simplify build and application configuration.
- Embedded server to avoid complexity in application deployment.
- Metrics, Health check, and externalized configuration
- Automatic config for Spring functionality – whenever possibleHere are two of the most important benefits Spring Boot brings in:
- Auto-configure applications based on the artifacts it finds on the class path
- Provide non-functional features common to applications in production, such as security or health checksHow Can We Set up a Spring Boot Application with Maven? We can include Spring Boot in a Maven project just like we would any other library. However, the best way is to inherit from the spring-boot-starter-parent project and declare dependencies to Spring Boot starter. Doing this lets our project reuse the default settings of Spring Boot.Inheriting the spring-boot-starter-parent project is straightforward – we only need to specify a parent element in pom.xml:
| <parent> <groupId> org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.1.RELEASE</version></parent> |
We can find the latest version of spring-boot-starter-parent on Maven Central.
Using the starter parent project is convenient, but not always feasible. For instance, if our company requires all projects to inherit from a standard POM, we cannot rely on the Spring Boot starter parent.
In this case, we can still get the benefits of dependency management with this POM element:
| <dependencyManagement> <dependencies> <dependency> <groupId> org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>2.1.1. RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies></dependencyManagement> |
Finally, we can add some dependencies to Spring Boot starters, and then we’re good to go.
What does the @SpringBootApplication annotation do internally?
As per the Spring Boot doc, the @SpringBootApplication annotation is equivalent to using @Configuration, @EnableAutoConfiguration, and @ComponentScan with their default attributes. Spring Boot enables the developer to use a single annotation instead of using multiple. But, as we know, Spring provided loosely coupled features that we can use for each individual annotation as per our project needs.
What is the Spring Initializer?
The Spring Initializer is a web application that generates a Spring Boot project with everything you need to start it quickly. As always, we need a good skeleton of the project; it helps you to create a project structure/skeleton properly.
What Spring Boot Starters Are Available Out There?
Dependency management is a crucial facet of any project. When a project is complex enough, managing dependencies may turn into a hectic, as there will be too many artifacts involved.
This is where Spring Boot starters come in handy. Each starter plays a role as a one-stop shop for all the Spring technologies we need. Other required dependencies are then transitively pulled in and managed in a consistent way.
All starters are under the org.springframework.boot group, and their names start with spring-boot-starter. This naming pattern makes it easy to find starters, especially when working with IDEs that support searching dependencies by name.
At the time of this writing, there are more than 50 starters at our disposal. The most commonly used are:
- spring-boot-starter: core starter, including auto-configuration support, logging, and YAML
- spring-boot-starter-aop: starter for aspect-oriented programming with Spring AOP and AspectJ
- spring-boot-starter-data-jpa: starter for using Spring Data JPA with Hibernate
- spring-boot-starter-jdbc: starter for using JDBC with the HikariCP connection pool
- spring-boot-starter-security: starter for using Spring Security
- spring-boot-starter-test: starter for testing Spring Boot applications
- spring-boot-starter-web: starter for building web, including RESTful, applications using Spring MVCHow to Disable a Specific Auto-Configuration?If we want to disable a specific auto-configuration, we can indicate it using the exclude attribute of the @EnableAutoConfiguration annotation. For instance, this code snippet neutralizes DataSourceAutoConfiguration: // other annotations
| @EnableAutoConfiguration (exclude = DataSourceAutoConfiguration.class)public class MyConfiguration { } |
If we enabled auto-configuration with the @SpringBootApplication annotation — which has @EnableAutoConfiguration as a meta-annotation — we could disable auto-configuration with an attribute of the same name:
// other annotations
| @SpringBootApplication (exclude = DataSourceAutoConfiguration.class)public class MyConfiguration { } |
We can also disable an auto-configuration with the spring.autoconfigure.exclude environment property. This setting in the application.properties file does the same thing as before:
| spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration |
How to Register a Custom Auto-Configuration?
To register an auto-configuration class, we must have its fully-qualified name listed under the EnableAutoConfiguration key in the META-INF/spring.factories file:
| org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.param.autoconfigure.CustomAutoConfiguration |
If we build a project with Maven, that file should be placed in the resources/META-INF directory, which will end up in the mentioned location during the package phase.
How to Tell an Auto-Configuration to Back Away When a Bean Exists?
To instruct an auto-configuration class to back off when a bean is already existent, we can use the @ConditionalOnMissingBean annotation. The most noticeable attributes of this annotation are:
- value: The types of beans to be checked
- name: The names of beans to be checkedWhen placed on a method adorned with @Bean, the target type defaults to the method’s return type:
| @Configurationpublic class CustomConfiguration { @Bean @ConditionalOnMissingBean public CustomService service ( ) { … }} |
How to Deploy Spring Boot Web Applications as Jar and War Files?
Traditionally, we package a web application as a WAR file, then deploy it into an external server. Doing this allows us to arrange multiple applications on the same server. During the time that CPU and memory were scarce, this was a great way to save resources.
However, things have changed. Computer hardware is fairly cheap now, and the attention has turned to server configuration. A small mistake in configuring the server during deployment may lead to catastrophic consequences.
Spring tackles this problem by providing a plugin, namely spring-boot-maven-plugin, to package a web application as an executable JAR. To include this plugin, just add a plugin element to pom.xml:
| <plugin> <groupId>org.springframework. boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId></plugin> |
With this plugin in place, we’ll get a fat JAR after executing the package phase. This JAR contains all the necessary dependencies, including an embedded server. Thus, we no longer need to worry about configuring an external server.
We can then run the application just like we would an ordinary executable JAR.
Notice that the packaging element in the pom.xml file must be set to jar to build a
JAR file:
| <packaging>jar</packaging> |
If we don’t include this element, it also defaults to jar.
In case we want to build a WAR file, change the packaging element to war:
| <packaging>war</packaging> |
And leave the container dependency off the packaged file:
| <dependency> <groupId>org.springframework. boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope></dependency> |
After executing the Maven package phase, we’ll have a deployable WAR file.
How to Use Spring Boot for Command Line Applications?
Just like any other Java program, a Spring Boot command line application must have a main method. This method serves as an entry point, which invokes the SpringApplication.run method to bootstrap the application:
| @SpringBootApplicationpublic class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class); // other statements }} |
The SpringApplication class then fires up a Spring container and auto-configures beans. Notice we must pass a configuration class to the run method to work as the primary configuration source. By convention, this argument is the entry class itself. After calling the run method, we can execute other statements as in a regular program.
What Are Possible Sources of External Configuration?
Spring Boot provides support for external configuration, allowing us to run the same application in various environments. We can use properties files, YAML files, environment variables, system properties, and command-line option arguments to specify configuration properties.
We can then gain access to those properties using the @Value annotation, a bound object via the @ConfigurationProperties annotation, or the Environment abstraction.
Here are the most common sources of external configuration:
•Command-line properties: Command-line option arguments are program arguments starting with a double hyphen, such as –server.port=8080. Spring Boot converts all the arguments to properties and adds them to the set of environment properties.
•Application properties: Application properties are those loaded from the application.properties file or its YAML counterpart. By default, Spring Boot searches for this file in the current directory, class path root, or their config subdirectory.
•Profile-specific properties: Profile-specific properties are loaded from the application-{profile}. properties file or its YAML counterpart. The {profile} placeholder refers to an active profile. These files are in the same locations as, and take precedence over, non-specific property files.
What is Spring Boot Devtools Used for?
Spring Boot Developer Tools, or DevTools, is a set of tools making the development process easier. To include these development-time features, we just need to add a dependency to the pom.xml file:
| <dependency> <groupId>org.springframework. boot</groupId> <artifactId>spring-boot-devtools</artifactId></dependency> |
The spring-boot-devtools module is automatically disabled if the application runs in production. The repackaging of archives also excludes this module by default. Hence, it won’t bring any overhead to our final product.
By default, DevTools applies properties suitable to a development environment. These properties disable template caching, enable debug logging for the web group, and so on. As a result, we have this sensible development-time configuration without setting any properties.
Applications using DevTools restart whenever a file on the classpath changes. This is a very helpful feature in development, as it gives quick feedback for modifications.
By default, static resources, including view templates, don’t set off a restart. Instead, a resource change triggers a browser refresh. Notice this can only happen if the LiveReload extension is installed in the browser to interact with the embedded LiveReload server that DevTools contains.
How to Write Integration Tests?
When running integration tests for a Spring application, we must have an ApplicationContext.
To make our life easier, Spring Boot provides a special annotation for testing – @SpringBootTest. This annotation creates an ApplicationContext from configuration classes indicated by its classes attribute.
In case the classes attribute isn’t set, Spring Boot searches for the primary configuration class. The search starts from the package containing the test up until it finds a class annotated with @SpringBootApplication or @SpringBootConfiguration.
Notice if we use JUnit 4, we must decorate the test class with
| @RunWith (SpringRunner.class). |
For detailed instructions, check out our tutorial on testing in Spring Boot.
What Is Spring Boot Actuator Used for?
“An actuator is a manufacturing term that refers to a mechanical device for moving or controlling something. Actuators can generate a large amount of motion from a small change.”
Essentially, Actuator brings Spring Boot applications to life by enabling production-ready features. These features allow us to monitor and manage applications when they’re running in production.
Integrating Spring Boot Actuator into a project is very simple. All we need to do is to include the spring-boot-starter-actuator starter in the pom.xml file:
| <dependency> <groupId>org.springframework. boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId></dependency> |
Spring Boot Actuator can expose operational information using either HTTP or JMX endpoints. Most applications go for HTTP, though, where the identity of an endpoint and the /actuator prefix form a URL path.
Here are some of the most common built-in endpoints Actuator provides:
•auditevents: Exposes audit events information
•env: Exposes environment properties
•health: Shows application health information
•httptrace: Displays HTTP trace information
•info: Displays arbitrary application information
•metrics: Shows metrics information
•loggers: Shows and modifies the configuration of loggers in the application
•mappings: Displays a list of all @RequestMapping paths
•scheduledtasks: Displays the scheduled tasks in your application
•threaddump: Performs a thread dump
What is a shutdown in the actuator?
Shutdown is an endpoint that allows the application to be gracefully shutdown. This feature is not enabled by default. You can enable this by using management.endpoint.shutdown.enabled=true in your application.properties file. But be careful about this if you are using this.
Is this possible to change the port of Embedded Tomcat server in Spring boot?
Yes, it’s possible to change the port. You can use the application.properties file to change the port. But you need to mention “server.port” (i.e. server.port=8081). Make sure you have application.properties in your project classpath; REST Spring framework will take care of the rest. If you mention server.port=0 , then it will automatically assign any available port.
Can we override or replace the Embedded Tomcat server in Spring Boot?
Yes, we can replace the Embedded Tomcat with any other servers by using the Starter dependencies. You can use spring-boot-starter-jetty or spring-boot-starter- undertow as a dependency for each project as you need.
Can we disable the default web server in the Spring Boot application?
The major strong point in Spring is to provide flexibility to build your application loosely coupled. Spring provides features to disable the web server in a quick configuration. Yes, we can use the application. properties to configure the web application type, i.e. spring.main.web-application-type=none.