BU Questions On Spring Boot
BU Questions On Spring Boot
Spring Boot is a Spring module that aims to simplify the use of the Spring framework
for Java development. It is used to create stand-alone Spring-based applications that
you can just run. So, it basically removes a lot of configurations and dependencies.
Aiming at the Rapid Application Development, Spring Boot framework comes with
the auto-dependency resolution, embedded HTTP servers, auto-configuration,
management endpoints, and Spring Boot CLI.
So, if you ask me why should anybody use Spring Boot, then I would say, Spring
Boot not only improves productivity but also provides a lot of conveniences to write
your own business logic.
1. Spring CLI – Spring Boot CLI allows you to Groovy for writing Spring boot
application and avoids boilerplate code.
2. Starter Dependency – With the help of this feature, Spring Boot aggregates
common dependencies together and eventually improves productivity
3. Auto-Configuration – The auto-configuration feature of Spring Boot helps in
loading the default configurations according to the project you are working on.
In this way, you can avoid any unnecessary WAR files.
4. Spring Initializer – This is basically a web application, which can create an
internal project structure for you. So, you do not have to manually set up the
structure of the project, instead, you can use this feature.
5. Spring Actuator – This feature provides help while running Spring Boot
applications.
6. Logging and Security – The logging and security feature of Spring Boot,
ensures that all the applications made using Spring Boot are properly secured
without any hassle.
Well, there are various approaches to create a Spring Boot application using maven,
but if I have to name a few, then following are the ways to create a Spring Boot
project/ application using maven:
There is no doubt in the fact that Spring Boot allows the developers to run the same
application in different environments. Well, this is done with the support it provides
for external configuration. It uses environment variables, properties files, command-
line arguments, YAML files, and system properties to mention the required
configuration properties. Also, the @value annotation is used to gain access to the
properties. So, the most possible sources of external configuration are as follows:
Q8. What are the Spring Boot starters and what are available the
starters?
Spring Boot starters are a set of convenient dependency management providers that
can be used in the application to enable dependencies. These starters, make
development easy and rapid. All the available starters come under the
org.springframework.boot group. Few of the popular starters are as follows:
Spring Actuator is a cool feature of Spring Boot with the help of which you can see
what is happening inside a running application. So, whenever you want to debug
your application, and need to analyze the logs you need to understand what is
happening in the application right? In such a scenario, the Spring Actuator provides
easy access to features such as identifying beans, CPU usage, etc. The Spring
Actuator provides a very easy way to access the production-ready REST points and
fetch all kinds of information from the web. These points are secured using Spring
Security’s content negotiation strategy.
Java 8 +
Spring Framework 5.1.9 +
Maven 3.3+
Gradle 4.4+
Thymeleaf is a server-side Java template engine used for web applications. It aims
to bring natural template for your web application and can integrate well with Spring
Framework and HTML5 Java web applications. To use Thymeleaf, you need to add
the following code in the pom.xml file:
1 <dependency>
2 <groupId>org.springframework.boot</groupId>
3 <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
4
Q13. Can we change the port of the embedded Tomcat
server in Spring boot?
Yes, we can change the port of the embedded tomcat server by using the application
properties file. In this file, you have to add a property of “server.port” and assign it to
any port you wish to. For example, if you want to assign it to 8081, then you have to
mention server.port=8081. Once you mention the port number, the application
properties file will be automatically loaded by Spring Boot and the required
configurations will be applied on to the application.
Spring Boot Dev Tools are an elaborated set of tools and aims to make the process
of developing an application easier. If the application runs in the production, then this
module is automatically disabled, repackaging of archives are also excluded by
default. So, the Spring Boot Developer Tools applies properties to the respective
development environments. To include the DevTools, you just have to add the
following dependency into the pom.xml file:
1 <dependency>
2 <groupId>org.springframework.boot</groupId>
3 <artifactId>spring-boot-devtools</artifactId>
</dependency>
4
Q15. Mention the steps to create a Spring Boot project
using Spring Initializer.
Spring Initializr is a web tool provided by Spring. With the help of this tool, you can
create Spring Boot projects by just providing project details. The following steps
need to be followed to create a Spring Boot project using Spring Initializer:
Choose the maven project and the required dependencies. Then, fill in the
other required details like Group, Artifact, and then click on Generate Project.
Once the project is downloaded, extract the project onto your system
Next, you have to import this project using the import option on the Spring
Tool Suite IDE
While importing the project, remember that you have to choose the
project type to be Maven and the source project should contain the
pom.xml file.
Once, all the above steps are followed you will see that the Spring Boot project is
created with all the required dependencies.
Spring Boot starter projects provide the required libraries to connect the application
with JDBC. So, for example, if you just have to create an application and connect it
with MySQL database, you can follow the below steps:
1 spring.datasource.url=jdbc:mysql://localhost:3306/example
2 spring.datasource.username=root
3 spring.datasource.password=edureka
spring.jpa.hibernate.ddl-auto=create-drop
4
Step 6: The main application.java class should have the following code:
1
package com.edureka;
2 import org.springframework.boot.SpringApplication;
3 import org.springframework.boot.autoconfigure.SpringBootApplication;
4 @SpringBootApplication
5 public class SampleApplication {
6 public static void main(String[] args) {
SpringApplication.run(SampleApplication.class, args);
7 }
8 }
9
Step 7: Next, you have to create a controller to handle the HTTP requests, by
mentioning the following code:
1
2 package com.edureka;
3 import org.springframework.web.bind.annotation.RequestMapping;
4 import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
5 import org.springframework.web.bind.annotation.RestController;
6 @RestController
7 public class JdbcController {
8 @Autowired
9 JdbcTemplate jdbc;
@RequestMapping("/insert")
10 public String index(){
11 jdbc.execute("insert into customers(name)values('Aryya')");
12 return "Data Entry Successful";
13 }
}
14
15
Step 8: Finally, execute this project as a Java application.
Step 9: Next, open the URL (localhost:8080/insert), and you will see the output as
Data Entry Successful. You can also go forward and check if the data is entered into
the table.
You can enable the HTTP/2 support in Spring Boot by: server.http2.enabled=true
@RequestMapping @RestController
This annotation is used to provide the routing
This annotation is used to add the
information and tells to Spring that any HTTP
@ResponseBody and @Controller
request must be mapped to the respective
annotation to the class
method.
To use this annotation, you have to import To use this annotation, you have to import
org.springframework.web. org.springframework.web.
bind.annotation.RequestMapping; bind.annotation.RestController;
Example: Consider you have a method example() which should map with /example
URL.
1
2 package com.edureka;
import org.springframework.web.bind.annotation.RequestMapping;
3 import org.springframework.web.bind.annotation.RestController;
4 @RestController
5 public class SampleController {
6 @RequestMapping("/example")
public String example(){
7
return"Welcome To Edureka";
8 }
9 }
10
Q19. What is Spring Boot CLI and how to execute the
Spring Boot project using boot CLI?
Spring Boot CLI is a tool supported by the official Spring Framework. The steps to
execute a Spring Boot project are as follows:
Download the CLI tool from the official site and extract the zip file. The bin
folder present in the Spring setup is used to execute the Spring Boot
application.
Since Spring Boot CLI executes groovy files, you need to create a groovy file
for Spring Boot application. So, to do that, open terminal and change the
current directory to the bin folder. Now, open a groovy file (for example
Sample.groovy)
In this file create a controller as follows:
JPA Hibernate
Hibernate is an implementation of Java
JPA is a Data Access Abstraction used to
Persistence API and offers benefits of loose
reduce the amount of boilerplate code
coupling
To create a custom endpoint in Spring Boot 2.x, you can use the @Endpoint
annotation. Spring Boot also exposes endpoints using @WebEndpointor,
@WebEndpointExtension over HTTP with the help of Spring MVC, Jersey, etc.
Spring Data aims to make it easy for the developers to use relational and non-
relational databases, cloud-based data services, and other data access
technologies. So, basically, it makes it easy for data access and still retains the
underlying data.
1 @EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
If the class is not on the classpath, then to exclude the auto-configuration, you have
to mention the following code:
1 @EnableAutoConfiguration(excludeName={Sample.class})
Apart from this, Spring Boot also provides the facility to exclude list of auto-
configuration classes by using the spring.autoconfigure.exclude property. You
can go forward, and add it either in the application.properties or add multiple classes
with comma-separated.
@SpringBootApplication @EnableAutoConfiguration
Used to enable auto-configuration and
Used in the main class or bootstrap class
component scanning in your project
It is a combination of @Configuration,
It is a combination of @Configuration and
@ComponentScan and
@ComponentScan annotations
@EnableAutoConfiguration annotations.
Q25. What are the steps to deploy Spring Boot web
applications as JAR and WAR files?
To deploy a Spring Boot web application, you just have to add the following plugin in
the pom.xml file:
1 <plugin>
2 <groupId>org.springframework.boot</groupId>
3 <artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
4
By using the above plugin, you will get a JAR executing the package phase. This
JAR will contain all the necessary libraries and dependencies required. It will also
contain an embedded server. So, you can basically run the application like an
ordinary JAR file.
Note: The packaging element in the pom.xml file must be set to jar to build a JAR
file as below:
1 <packaging>jar</packaging>
Similarly, if you want to build a WAR file, then you will mention
1 <packaging>war</packaging>
Q.26 Can you give an example for ReadOnly as true in
Transaction management?
Consider a scenario, where you have to read data from the database. For example,
let us say you have a customer database, and you want to read the customer details
such as customerID, and customername. To do that, you will set read-only on the
transaction as we do not want to check for the changes in the entities.
To deploy a different server with Spring Boot, follow the below steps:
Note: The steps to deploy the WAR file on the server is dependent on the server you
choose.
1 @Component
2 @ConfigurationProperties("example")
3 public class SampleConfiguration {
4 private int number;
private boolean value;
5
private String message;
6
According to the above snippet, the values configured in application.properties will
be as follows:
1 example.number: 100
2 example.value: true
3 example.message: Dynamic Message
Q29. Can we create a non-web application in Spring Boot?
Yes, we can create a non-web application by removing the web dependencies from
the classpath along with changing the way Spring Boot creates the application
context.
The advantages of the YAML file than a properties file is that the data is stored in a
hierarchical format. So, it becomes very easy for the developers to debug if there is
an issue. The SpringApplication class supports the YAML file as an alternative to
properties whenever you use the SnakeYAML library on your classpath. The
different ways to load a YAML file in Spring Boot is as follows:
Use YamlMapFactoryBean to load YAML as a Map
Use YamlPropertiesFactoryBean to load YAML as Properties
When we use the Spring Boot Auto Configuration, automatically the spring-boot-
starter-data-jpa dependency gets added to the pom.xml file. Now, since this
dependency has a transitive dependency on JPA and Hibernate, Spring Boot
automatically auto-configures Hibernate as the default implementation for JPA,
whenever it sees Hibernate in the classpath.
Spring Data REST is used to expose the RESTful resources around Spring Data
repositories. Consider the following example:
1 {
2 "customername": "Rohit"
3 }
Response Content
1 {
2 "customername": "Rohit"
"_links": {
3 "self": {
4 "href": "<a href="http://localhost:8080/sample/1">http://localhost:8080/sample/
5 1</a>"
6 },
"sample": {
7
"href": "<a href="http://localhost:8080/sample/1">http://localhost:8080/sample/
8 1</a>"
9 }
10 }
Observe that the response content contains the href of the newly created resource.
consumes = “text/plain”
consumes = {“text/plain”, “application/*”}
Q35. In which layer, should the boundary of a transaction
start?
The boundary of the transaction should start from the Service Layer since the logic
for the business transaction is present in this layer itself.
path – This section is used to mention the segment under which the resource
is to be exported.
collectionResourceRel – This value is used to generate links to the collection
resource.
Since Spring Boot supports Log4j2 for logging a configuration, you have to exclude
Logback and include Log4j2 for logging. This can be only done if you are using the
starters project.
Profiles are used to provide a way to segregate the different parts of the application
configuration and make it available for various environments. So, basically, any
@Component or a @Configuration can be marked with a @Profile to limit as it is
loaded. Consider you have multiple environments,
Dev
QA
Stage
Production
Now, let’s say, you want to have different application configuration in each of the
environments, you can use profiles to have different application configurations for
different environments. So, basically, Spring and Spring Boot provide features
through which you can specify:
The steps to add a custom JS code with Spring Boot are as follows:
Now, create a folder and name it static under the resources folder
In this folder, you can put the static content in that folder
Note: Just in case, the browser throws an unauthorized error, you either disable the
security or search for the password in the log file, and eventually pass it in the
request header.
To instruct an auto-configuration class to back off when a bean exists, you have to
use the @ConditionalOnMissingBean annotation. The attributes of this annotation
are as follows:
If H2 is not present in the classpath, then you see the following error:
Cannot determine embedded database driver class for database type NONE
To resolve this error, add H2 to the pom.xml file, and restart your server.
The following code snippet can be added to add the dependency:
web starter
mysql
data JPA starter
To include the dependencies refer to the following code:
1
2 <dependency>
3 <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
4 </dependency>
5 <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
6 <dependency>
7 <groupId>mysql</groupId>
8 <artifactId>mysql-connector-java</artifactId>
<version>8.0.14</version>
9 </dependency><dependency>
10 <groupId>org.springframework.boot</groupId>
11 <artifactId>spring-boot-starter-data-jpa</artifactId>
12 </dependency>
13
It is used to create stand alone spring based application that you can just
run because it needs very little spring configuration.
o Web Development
o SpringApplication
o Application events and listeners
o Admin features