Prev Next

Spring / Spring Boot

1. What is Spring Boot? 2. Advantages of using Spring Boot. 3. What are the limitations of Spring Boot? 4. Can we use spring boot for applications that are not built using Spring framework? 5. What is the latest version of Spring Boot? 6. Explain CommandLineRunner interface in Spring boot. 7. Difference between CommandLineRunner and ApplicationRunner in Spring Boot. 8. What are microservices? 9. What are the components of Spring Boot? 10. What is name of the configuration file that you use in Spring boot? 11. What is actuator in Spring boot? 12. What are the embedded containers supported by Spring Boot? 13. Explain spring boot initializr. 14. How to write Test cases using Spring Boot? 15. How do I add custom JS code with Spring Boot? 16. How do I change the port of Embedded Server in Spring boot Application? 17. Explain Spring boot starters. 18. Mention some of the Spring Boot starters. 19. Disadvantages of Spring Boot. 20. How to create an ActiveMQ Spring Boot Application? 21. How do you reload Spring Boot changes without restarting the server? 22. How to customize a banner printed during spring boot app start up? 23. How do you upgrade from an earlier version of Spring boot? 24. How to create an executable jar for your spring boot application using Maven? 25. Can you get spring boot working with ant-based projects? 26. How do I change from tomcat to other embedded containers? 27. How do I change tomcat port in my spring boot application? 28. What is the role of @SpringBootApplication annotation? 29. Can you run Spring boot application using Maven plugin? 30. Advantages of using Spring boot developer tools. 31. What is auto-configuration in Spring boot? 32. Why do we need starter dependencies in spring boot? 33. What are the application events sent by SpringApplication? 34. What is thymeleaf? 35. How does the Devtool provided Auto-restart works in Spring Boot? 36. What is WebApplicationType in Spring Boot? 37. Difference between CommandLineRunner and ApplicationRunner in Spring Boot? 38. Why do we need EnvironmentPostProcessor in Spring Boot? 39. Default logging system of Spring Boot. 40. Why spring boot is "opinionated"? 41. How to enable auto-reload of applications on changes in Spring Boot?
Could not find what you were looking for? send us the question and we would be happy to answer your question.

What is Spring Boot?

Spring Boot is a framework for building and running Spring applications by providing defaults for code and annotation configuration to quick start new Spring projects within no time. It follows "Opinionated Defaults Configuration" Approach to avoid lot of boilerplate code and configuration to improve Development, Unit Test and Integration Test Process.

One of the biggest challenges faced by the Spring developers is that amount of time they spent on configuring and bootstarting their spring applications.With growing number of frameworks with Spring community, it is necessary to have a common framework that solves the configurations. Spring Boot simply scan the classpath and add the required libraries from various repositories. This improves the productivity and saves lot of time for the developers.

Advantages of using Spring Boot.

To ease the Java-based applications Development, Unit Test and Integration Test Process.

To reduce development, unit Test and integration Test time by providing some defaults.

To increase productivity.

It avoids writing lots of boilerplate code, annotations and XML configuration.

It is very easy to integrate Spring Boot Application with its Spring Ecosystem like Spring JDBC, Spring ORM, Spring Data, Spring Security etc. It follows the "Opinionated Defaults Configuration" approach to reduce developer effort.

It provides Embedded HTTP servers like Tomcat, Jetty etc. to develop and test our web applications very easily.

It provides CLI (Command Line Interface) tool to develop and test Spring Boot(Java or Groovy) Applications from command prompt very easily and quickly.

It provides plugins to develop and test Spring Boot Applications very easily using build Tools like Maven and Gradle.

It provides plugins to work with embedded and in-memory Databases very easily.

What are the limitations of Spring Boot?

We can convert all kinds of spring projects into Spring Boot Applications however it is time consuming process to convert existing or legacy Spring Framework projects into Spring Boot Applications.

Can we use spring boot for applications that are not built using Spring framework?

No. Spring Boot is limited to work with Spring based applications (Java/groovy).

What is the latest version of Spring Boot?

2.1.6.RELEASE is the latest version.

Explain CommandLineRunner interface in Spring boot.

CommandLineRunner Interface is used to indicate that a bean should run when it is contained within a Spring application. Multiple CommandLineRunner beans can be defined within the same application context and can be ordered using the Ordered interface or @Order annotation.

Difference between CommandLineRunner and ApplicationRunner in Spring Boot.

Both are similar in terms of functionality and the difference is that If you need access to ApplicationArguments instead of the raw String array consider using ApplicationRunner than CommandLineRunner.

What are microservices?

Micro service is an architectural style that structures an application as a collection of loosely coupled services, which implement business capabilities. The microservice architecture enables the continuous delivery/deployment of large, complex applications. It also enables an organization to evolve its technology stack.

What are the components of Spring Boot?

The components are,

  • Spring Boot Starter,
  • Spring Boot AutoConfigurator,
  • Spring Boot Actuator,
  • Spring Boot CLI,
  • Spring Boot IDE,
  • and Spring Boot Initilizr.
What is name of the configuration file that you use in Spring boot?

Configuration file used in Spring boot projects is application.properties. It is used to override all default configurations.

What is actuator in Spring boot?

Spring boot actuator is one of the important features of Spring boot. It is used to access current state of running application in production environment. There are various metrics which you can use to check current state of the application.

Spring boot actuator provides restful web services end points which you can simply use and check various metrics. For example, /metrics end point will display metrics such as free memory, processors, uptime and other properties,

What are the embedded containers supported by Spring Boot?

Spring boot supports embedded containers such as Tomcat (default), Jetty and undertow servers.

Explain spring boot initializr.

Spring Boot Initilizr is a Spring Boot tool to bootstrap Spring Boot or Spring Applications easily.

Spring Boot Initilizr is available in the below forms:

  • Spring Boot Initilizr With Web Interface,
  • Spring Boot Initilizr With IDEs/IDE Plugins,
  • Spring Boot Initilizr With Spring Boot CLI,
  • Spring Boot Initilizr With ThirdParty Tools.

A demo of the spring initializr web interface is available here.

How to write Test cases using Spring Boot?

Spring Boot provides the @SpringBootTest annotation for writing Unit Test Cases.

How do I add custom JS code with Spring Boot?

Create a folder called static under resources folder and put your static content in that folder. For your example the path to myStatic.js would be resources\static\js\myStatic.js.

You may refer to it in jsp as shown below.

<script src="/js/myStatic.js"></script>
How do I change the port of Embedded Server in Spring boot Application?

You may change the port in spring boot by adding a property server.port = <port> in application.properties file.

Explain Spring boot starters.

Spring Boot Starters are a set of convenient dependency descriptors that you can include in your application. You get all the Spring and related technology at one-stop-shop that you need without having to deal with sample code and copy paste loads of dependency descriptors. It minimizes the effort.

For example, to work with Spring & JPA for database access project include only the spring-boot-starter-data-jpa dependency in your project POM.

Mention some of the Spring Boot starters.
  • spring-boot-starter-data-jpa for Spring Data JPA.
  • spring-boot-starter-web for Spring Web applcation and creating Restful services.
  • spring-boot-starter-security for Spring security.
  • spring-boot-starter-test for unit testing your application.
  • spring-boot-starter-batch for creating spring batch jobs.

Please find the complete list of spring boot starters here.

Disadvantages of Spring Boot.

Spring boot may include dependencies that are not used thereby causing huge deployment file size.

Turning legacy spring applications into Spring boot requires a lot of effort and a time-consuming process.

Limited control of your application.

How to create an ActiveMQ Spring Boot Application?

Use Spring boot starter spring-boot-starter-activemq dependency in your applcation POM xml file and it takes care of all dependencies and configuration required for activeMQ projects.

Under application.properties add a property spring.activemq.broker-url along with the URL to configure external ActiveMQ in your application.

How do you reload Spring Boot changes without restarting the server?

Using Spring Boot Dev Tools module we can achieve auto reload. It is a powerful tool that helps developers to lessen the development cycle and enable easy deployment and testing during development.

To enable this feature, add the below dependency to Maven POM file.

<dependencies>
    <dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-devtools</artifactId>
    </dependency>
</dependencies>

The below configuration is for Gradle:

configurations {
	developmentOnly
	runtimeClasspath {
		extendsFrom developmentOnly
	}
}
dependencies {
	developmentOnly("org.springframework.boot:spring-boot-devtools")
}

How to customize a banner printed during spring boot app start up?

The banner that is printed on start up can be changed by adding a banner.txt file to your classpath or by setting the spring.banner.location property to the location. In addition to a text file, you can also add a banner.gif, banner.jpg, or banner.png image file to your classpath or set the spring.banner.image.location property. Images are converted into an ASCII art representation and printed above any text banner.

How do you upgrade from an earlier version of Spring boot?

When upgrading Spring boot, some properties may have been renamed or removed. Spring Boot provides a way to analyze your application's environment and print diagnostics at startup, but also temporarily migrate properties at runtime. To enable that feature, add the following dependency to your project:

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-properties-migrator</artifactId>
	<scope>runtime</scope>
</dependency>

Once you're done with the migration, remove this module from your project's dependencies.

How to create an executable jar for your spring boot application using Maven?

To create an executable jar, add the spring-boot-maven-plugin to our pom.xml. Insert the following lines just below the dependencies section in your project's POM.xml:

<build>
   <plugins>
	<plugin>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-maven-plugin</artifactId>
	</plugin>
   </plugins>
</build>

Can you get spring boot working with ant-based projects?

It is possible to get Spring Boot to work with other build systems such as Ant, but they are not well supported. It is recommended to use with Gradle or Maven.

How do I change from tomcat to other embedded containers?

Tomcat is the default embedded container when we specify web since spring-boot-starter-web dependency declares spring-boot-starter-tomcat as its dependency.

To change from tomcat to Jetty, we need to remove tomcat dependency by specifying the exclusion in pom.xml if you are using maven.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>

After removing the tomcat dependency, the next step is to specify the dependency for jetty.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jetty</artifactId>
</dependency>

Now build your project using maven and run your application to see that jetty in use.

How do I change tomcat port in my spring boot application?

The default tomcat port is 8080. To change it, specify the server.port property with desired port in the application properties or yaml.

application.properties:

server.port=8091

application.yml:

server:
  port: 8091

Alternatively, you may pass the property as JVM option as -Dserver.port=8091.

What is the role of @SpringBootApplication annotation?

@SpringBootApplication annotation can be used to enable those three features below.

  • @EnableAutoConfiguration enable Spring Boot's auto-configuration mechanism.
  • @ComponentScan enable @Component scan on the package where the application is located.
  • @Configuration allow to register extra beans in the context or import additional configuration classes.

The @SpringBootApplication annotation is equivalent to using @Configuration, @EnableAutoConfiguration, and @ComponentScan with its default attributes.

package net.javapedia.springboot.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication // same as using @Configuration @EnableAutoConfiguration @ComponentScan
public class MyApplication {

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

}

Can you run Spring boot application using Maven plugin?

Yes, the Spring Boot Maven plugin includes a run goal that is used to quickly compile and run your application.

mvn spring-boot:run

Similarly, Spring Boot Gradle plugin also includes a bootRun task that can be used to run your application

gradle bootRun

Advantages of using Spring boot developer tools.
  • Property Defaults: spring-boot-devtools module automatically applies sensible development-time configuration by disabling properties such as caching to false during development; Sets DEBUG mode for web logging group which helps get more information about incoming request.
  • Automatic Restart: Applications that use spring-boot-devtools restart automatically whenever files on the classpath change. This can be a useful feature when working in an IDE, as it restarts automatically with the code changes.
  • Live Reload: The spring-boot-devtools module includes an embedded LiveReload server that can be used to trigger a browser refresh when a resource is changed.
  • Global Settings: You can configure global devtools settings by adding a file named .spring-boot-devtools.properties to your $HOME folder. Any properties added to this file apply to all Spring Boot applications on your machine that use devtools.
  • Remote Applications: spring-boot-devtools provides out of the box remote debugging capabilities via HTTP, to have this feature it is required that spring-boot-devtools are packaged as part of the application. This can be achieved by disabling excludeDevtools configuration in the plugin in maven.
What is auto-configuration in Spring boot?

Spring boot automatically configures a lot of dependencies just by its availability in the classpath. For example, it can auto configure tomcat if the server container is not available. This is why spring boot is opinionated because it auto configure many dependencies if it is not needed and we can override auto configuration settings as needed.

Auto configuration is disabled by default and use one of the annotations @SpringBootApplication or @EnableAutoConfiguration on the Main class to enable the feature.

Why do we need starter dependencies in spring boot?

Starter dependencies combine many libraries into one based on its functionality/dependency and acts as a single starter package.

It eliminates the need to manually add dependencies in build script and also manages compatibility and version mismatch issues.

What are the application events sent by SpringApplication?

An ApplicationStartingEvent is sent at the start of a run but before any processing, except for the registration of listeners and initializers.

An ApplicationEnvironmentPreparedEvent is sent when the Environment to be used in the context is known but before the context is created.

An ApplicationPreparedEvent is sent just before the refresh is started but after bean definitions have been loaded..

An ApplicationStartedEvent is sent after the context has been refreshed but before any application and command-line runners have been called.

An ApplicationReadyEvent is sent after any application and command-line runners have been called. It indicates that the application is ready to service requests.

An ApplicationFailedEvent is sent if there is an exception on startup.

package net.javapedia.applicationeventdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;

@SpringBootApplication
public class ApplicationEventDemoApplication {

	public static void main(String[] args) {

		SpringApplication myApp = new SpringApplication(ApplicationEventDemoApplication.class);
		myApp.addListeners(new MyApplicationListener());
		myApp.run(args);

	}


	static class MyApplicationListener implements ApplicationListener<ApplicationEvent> {

		@Override
		public void onApplicationEvent(ApplicationEvent event) {
			System.out.println("Event triggered: " + event );
		}
	}

}

Example for ApplicationFailedEvent

package net.javapedia.applicationeventdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;

@SpringBootApplication
public class ApplicationEventDemoApplication {

	public static void main(String[] args) {

		SpringApplication myApp = new SpringApplication(ApplicationEventDemoApplication.class);
		myApp.addListeners(new MyApplicationListener());
		myApp.run(null);

	}


	static class MyApplicationListener implements ApplicationListener<ApplicationEvent> {

		@Override
		public void onApplicationEvent(ApplicationEvent event) {
			System.out.println("Event triggered: " + event );
		}
	}

}

What is thymeleaf?

Thymeleaf is a server-side Java template engine for web applications to bring elegant natural templates for your web apps.

It is easy to integrate with spring Framework and works well with HTML5 Java-based web applications.

In order to use thymeleaf in your project, add the dependency in your project's dependency as shown below.

Maven:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
    <version>2.1.9.RELEASE</version>
</dependency>

Gradle:

compile group: 'org.springframework.boot', name: 'spring-boot-starter-thymeleaf', version: '2.1.9.RELEASE'

How does the Devtool provided Auto-restart works in Spring Boot?

The Spring Boot restart technology works by using 2 classloaders.

Class that don't change ( 3rd party jars, as an example) are loaded into base classloader. Classes that actively change during development are loaded into restart classloader.

When the application restarts, the restart classloader is destroyed and new one is created. This makes the application restarts faster than "cold restart" as the base loader is already available.

What is WebApplicationType in Spring Boot?

WebApplicationType is an enumeration that represent possible types of web application.

  • NONE: The application is NOT an web application and should not start an embedded web server.
  • REACTIVE: The application should run as a reactive web application and should start an embedded reactive web server.
  • SERVLET: The application should run as a servlet-based web application and should start an embedded servlet web server.

We may call setWebApplicationType(WebApplicationType.NONE) , for example, to choose the type as needed.

Difference between CommandLineRunner and ApplicationRunner in Spring Boot?

Both interfaces, CommandLineRunner and ApplicationRunner works in the same way and offers a single run method.

The difference is, the CommandLineRunner interface provides access to the application arguments as a simple String array, while ApplcationRunner uses the ApplicationArguments interface, which provides access to both the raw String[] arguments as well as parsed option and non-option arguments.

Find more information here.

Why do we need EnvironmentPostProcessor in Spring Boot?

The EnvironmentPostProcessor interface allows us to manipulate the Environment before even the application starts. This interface allows us to create support for encrypting/decrypting property values/ add new properties etc.

Default logging system of Spring Boot.

Spring Boot uses commons-logging and LogBack implementation by default.

Why spring boot is "opinionated"?

This question is already answered here.

How to enable auto-reload of applications on changes in Spring Boot?

You may enable auto-reload of spring boot application by adding the spring-boot-devtools dependency in the pom.xml file.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <optional>true
</dependency>
«
»
Spring cloud

Comments & Discussions