Top 85+ Spring Boot QA For 2023 Java Developer
Top 85+ Spring Boot QA For 2023 Java Developer
Spring Boot is called a microservice framework that is built on top of the spring
framework. This can help developers to focus more on convention rather than
configuration.
1. The main aim of Spring boot is to give you a production-ready application. So,
the moment you create a spring-boot project, it is runnable and can be
executed/deployed on the server.
2. It comes with features like autoconfiguration, auto dependency resolution,
embedded servers, security, health checks which enhances the productivity of
a developer.
One of the ways to create a spring boot project in eclipse is by using Spring Initializer.
You can go to the official website of spring and add details such as version, select
maven or Gradle project, add your groupId, artifactId, select your required
dependencies and then click on CREATE PROJECT.
Once the project is created, you can download it and extract and import it in your
eclipse or STS.And see your project is ready! To Install Spring Boot in Eclipse – Go to
Eclipse IDE, click on “Help”->then go to Eclipse marketplace->and type Spring IDE and
click on the finish button.
Whenever you will create your spring boot application and run it, Spring boot will
automatically detect the embedded tomcat server and deploy your application on
tomcat.After successful execution of your application, you will be able to launch your
rest endpoints and get a response.
Spring boot-
An actuator is one of the best parts of spring boot which consists of production-ready
features to help you monitor and manage your application.
With the help of an actuator, you can monitor what is happening inside the running
application.
Actuator dependency figures out the metrics and makes them available as a new
endpoint in your application and retrieves all required information from the web. You can
identify beans, the health status of your application, CPU usage, and many more with
the actuator. By using @Endpoint annotation, you can create a custom endpoint.
To create a war file in spring boot you need to define your packaging file as war in your
pom.xml(if it is maven project).
Then just do maven clean and install so that your application will start building. Once
the build is successful, just go into your Target folder and you can see .war file
generated for your application.
JPA is basically Java Persistence API. It’s a specification that lets you do ORM when
you are connecting to a relational database which is Object-Relational Mapping.
So, when you need to connect from your java application to relational database, you
need to be able to use something like JDBC and run SQL queries and then you get the
results and convert them into Object instances.
ORM lets you map your entity classes in your SQL tables so that when you connect to
the database , you don’t need to do query yourself, it’s the framework that handles it for
you.
And JPA is a way to use ORM, it’s an API which lets you configure your entity classes
and give it to a framework so that the framework does the rest.
✓ Then you can map your entities with your db tables using JPA.
✓ And with the help of save() method in JPA you can directly insert your data into your
database
@RestController
@RequestMapping("/greatleasrning")
public class Controller {
@Autowired
private final TechTalkDebuRepository TechTalkDebuRepository;
public Controller(TechTalkDebuRepository TechTalkDebuRepository) {
}
In above case, your data which may be in JSON format can be inserted successfully
into database.
@RequestMapping(method = RequestMethod.POST)
ResponseEntity<?> insert(@RequestBody Course course) {
TechTalkDebuRepository.save(course);
return ResponseEntity.accepted().build();
}
}
For example: If we make use of Spring JDBC, the spring boot autoconfiguration feature
automatically registers the DataSource and JDBCTemplete bean.
This entire process of automatically declaring the framework specific bean without the
need of writing the xml code or java config code explicity is called Autoconfiguration
which is done by springBoot with the help of an annotation called
@EnableAutoconfiguration alternatively @SpringBootApplication.
This is quite common error in spring boot application which says 404(page not found).
We can mostly resolve this in 3 ways:
You can use the following steps to connect your application with MySQL database.
1. First create a database in MySQL with create DATABASE student;
2. Now, create a table inside this DB:
CREATE TABLE student(studentid INT PRIMARY KEY NOT NULL
AUTO_INCREMENT, studentname VARCHAR(255));
3. Create a SpringBoot application and add JDBC, MySQL and web dependencies.
4. In application.properties, you need to configure the database.
spring.datasource.url=jdbc:mysql://localhost:3306/studentDetails
spring.datasource.username=system123
spring.datasource.password=system123
spring.jpa.hibernate.ddl-auto=create-drop
package com.student;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class JdbcController {
@Autowired
JdbcTemplate jdbc;
@RequestMapping("/save")
public String index(){
jdbc.execute("insert into student (name)values(TechTalkDebus)");
return "Data Entry Successful";
}
}
● Using log4j2:
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
// [...]
Logger logger = LogManager.getLogger(LoggingController.class);
● Using Lombok:
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
<scope>provided</scope>
</dependency>
Now you can create a loggingController and add the @Slf4j annotation to it. Here we
would not create any logger instances.
@RestController
@Slf4j
public class LoggingController {
@RequestMapping("/logging")
public String index() {
log.trace("A TRACE Message");
log.debug("A DEBUG Message");
log.info("An INFO Message");
log.warn("A WARN Message");
log.error("An ERROR Message");
So, there are many such ways in spring boot to use logger
One of the way to bootstrap your spring boot application is using Spring Initializer.
you can go to the official website of spring and select your version, and add you
groupID, artifactId and all the required dependencies.
And then you can create your restEndpoints and build and run your project.
There you go, you have bootstrapped your spring boot application.
To create a jar file in spring boot you need to define your packaging file as jar in your
pom.xml(if it is maven project).
Then just do maven build with specifying goals as package so that your application will
start building.
Once the build is successful, just go into your Target folder and you can see .jar file
generated for you application.
Dependency injection is a way through which the Spring container injects one object
into another. This helps for loose coupling of components.
For example: if class student uses functionality of department class, then we say
student class has dependency of Department class. Now we need to create object of
class Department in your student class so that it can directly use functionalities of
department class is called dependency injection.
One of the way for storing image in MongoDB is by using Spring Content. And also you
should have the below dependency in your pom.xml
<dependency>
<groupId>com.github.paulcwarren</groupId>
<artifactId>spring-content-mongo-boot-starter</artifactId>
<version>0.0.10</version>
</dependency>
@Configuration
public class Config
@Bean
public GridFsTemplate gridFsTemplate() throws Exception {
return new GridFsTemplate(mongoDbFactory(), mappingMongoConverter());
Now add attributes so that your content will be associated to your entity.
@ContentId
private String contentId;
@ContentLength
private long contentLength = 0L;
@MimeType
private String mimeType = "text/plain";
And last but not the least, add a store interface.
@StoreRestResource(path="TechTalkDebuImages")
public interface TechTalkDebuImageStore extends ContentStore<Candidate,
String> {
}
That’s all you have to do to store your images in mongoDb using Springboot.
1. spring-boot-starter-data-jpa
2. h2 (you can also use any other database)
Now, provide all the database connection properties in application.properties file of your
application in order to connect your JPA code with the database.
Here we will configure H2 database in application.properties file:
spring.datasource.url=jdbc:h2:file:~/test
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=test
spring.datasource.password=test
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
Adding the above properties in your application.properties file will help you to interact
with your database using JPA repository interface.
1. It allows convention over configuration hence you can fully avoid XML
configuration.
2. SpringBoot reduces lots of development time and helps to increase
productivity.
3. Helps to reduce a lot of boilerplate code in your application.
4. It comes with embedded HTTP servers like tomcat, Jetty, etc to develop and
test your applications.
5. It also provides CLI (Command Line Interface) tool which helps you to
develop and test your application from CMD.
Thymeleaf is a server-side java template engine which helps processing and creating
HTML, XML, JavaScript , CSS, and text. Whenever the dependency in pom.xml (in case
of maven project) is find, springboot automatically configures Thymeleaf to serve
dynamic web content.
Dependency: spring-boot-starter-thymeleaf
We can place the thyme leaf templates which are just the HTML files in
src/main/resources/templates/ folder so that spring boot can pick those files and
renders whenever required.
Thymeleaf will parse the index.html and will replace the dynamic values with its actual
value that is been passed from the controller class.
That’s it, once you run your Spring Boot application and your message will be rendered
in web browsers.
This is one of the amazing features provided by Spring Boot, where it restarts the spring
boot application whenever any changes are being made in the code.
Here, you don’t need to right-click on the project and run your application again and
again. Spring Boot dev tools does this for you with every code change.
Dependency to be added is: spring-boot-devtools
The main focus of this module is to improve the development time while working on
Spring Boot applications.
22. Can we change the port of the embedded Tomcat server in Spring
boot?
Yes, you can change the port of embedded Tomcat server in Spring boot by adding the
following property in your application.properties file.
server.port=8084
The default port number of the tomcat server to run the spring boot application is 8080,
which is further possible to change it.
So we can change the port of tomcat following ways given below:-
✓ Using application.properties
✓ Using application.yml
✓ Using EmbeddedServletContainerCustomizer interface.
✓ Using WebServerFactoryCustomizer interface.
✓ Using Command-Line Parameter.
spring.datasource.url=jdbc:mysql://localhost:3306/studentDetails
spring.datasource.username=system123
spring.datasource.password=system123 spring.jpa.hibernate.ddl-
auto=create-drop
package com.student;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class JdbcController {
@Autowired
JdbcTemplate jdbc;
@RequestMapping("/save")
public String index(){
jdbc.execute("insert into student (name)values(TechTalkDebus)");
return "Data Entry Successful";}}
Step 6: Run the application and check the entry in your Database.
Step 7: You can also go ahead and open the URL and you will see “Data Entry
Successful” as your output.
The global request path that needs to be mapped on a controller class can be done by
using @RequestMapping at class-level. If you need to map a particular request
specifically to some method level.
@RestController
@RequestMapping("/TechTalkDebu")
public class TechTalkDebuController {
@RequestMapping("/")
String TechTalkDebu(){
return "Hello from TechTalkDebu ";
}
@RequestMapping("/welcome")
String welcome(){
return "Welcome from TechTalkDebu";
}
}
@RestController
@RequestMapping("bank-details")
public class DemoRestController{
@GetMapping("/{id}",produces ="application/json")
public Bank getBankDetails(@PathVariable int id){
return findBankDetailsById();
}
}
1. You can exclude the attribute of @EnableAutoConfiguration where you don’t want
it to be configured implicity in order to disable the spring boot’s auto-configuration
feature.
2. Another way of disabling auto-configuration is by using the property file:
For example:
spring.autoconfigure.exclude=
org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,org.
springframework.boot.autoconfigure.data.MongoDataConfiguration
27. Mention the advantages of the YAML file than Properties file and the
different ways to load
For example:
spring:
profiles:
active:
-test
---
spring:
profiles:
active:
-prod
---
spring:
profiles:
active:
-development
By using Spring Data Rest, you have access to all the RESTful resources that revolves
around Spring Data repositories.
Refer the below example:
Now you can use the POST method in the below manner:
{
"Name":"TechTalkDebu"
}
{
"Name":"TechTalkDebu"
}
__________
{
"name": "Hello TechTalkDebu "
"_links": {
"self": {
"href": "<a href="http://localhost:8080/sample/1">http://localhost:8080/
TechTalkDebu /1</a>"
},
" TechTalkDebu ": {
"href": "<a href="http://localhost:8080/sample/1">http://localhost:8080/
TechTalkDebu /1</a>"
}
}
In the above, you can see the response of the newly created resource.
The application has different stages-such as the development stage, testing stage,
production stage and may have different configurations based on the environments.
With the help of spring boot, you can place profile-specific properties in different files
such as
Application-{profile}.properties
In the above, you can replace the profile with whatever environment you need, for
example, if it is a development profile, then application-development.properties file
will have development specific configurations in it.
So, in order to have profile-specific configurations/properties, you need to specify an
active profile.
@RestController
@RequestMapping("/greatleasrning")
public class Controller {
@Autowired
private final TechTalkDebuRepository TechTalkDebuRepository;
public Controller(TechTalkDebuRepository TechTalkDebuRepository) {
this. TechTalkDebuRepository = TechTalkDebuRepository;
}
In the above case, your data which may be in JSON format can be inserted successfully
into the database.
@RequestMapping(method = RequestMethod.POST)
ResponseEntity<?> insert(@RequestBody Course course) {
TechTalkDebuRepository.save(course);
return ResponseEntity.accepted().build();
}
}
You can create a simple and default login page in spring boot, you can make use of
Spring security. Spring security secures all HTTP endpoints where the user has to login
into the default HTTP form provided by spring.
We need to add spring-boot-starter-security dependency in your pom.xml or
build.gradle and a default username and password can be generated with which you
can log in.
In order to use crud repository in spring boot, all you have to do is extend the crud
repository which in turn extends the Repository interface as a result you will not need to
implement your own methods.
Create a simple spring boot application which includes below dependency:
spring-boot-starter-data-jpa, spring-boot-starter-data-rest
package com.TechTalkDebu;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import
org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource
public interface TechTalkDebu extends CrudRepository<Candidate, Long>
{
public List<Candidate> findById(long id);
In order to run spring boot jar from the command line, you need to update you
pom.xml(or build.gradle) of your project with the maven plugin.
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
Now, Build your application and package it into the single executable jar. Once the jar is
built you can run it through the command prompt using the below query:
35. What is Spring Boot CLI and how to execute the Spring Boot project
using boot CLI?
Spring Boot CLI is nothing but a command-line tool which is provided by Spring so that
you can develop your applications quicker and faster.
To execute your spring boot project using CLI, you need first to download CLI from
Spring’s official website and extract those files. You may see a bin folder present in the
Spring setup which is used to execute your spring boot application.
As Spring boot CLI allows you to execute groovy files, you can create one and open it in
the terminal.
And then execute ./spring run filename.groovy;
@RestController
@RequestMapping("bank-details")
public class DemoRestController{
@GetMapping("/{id}",produces ="application/json")
public Bank getBankDetails(@PathVariable int id){
return findBankDetailsById();
}
}
Consider a scenario, where there are no stockDetails in the DB and still, whenever you
hit the GET method you get 200(OK) even though the resource is not found which is not
expected. Instead of 200, you should get 404 error.
So to handle this, you need to create an exception, in the above scenario
“StockNotFoundException”.
GetMapping("/stocks/{number}")
public Stock retriveStock(@PathVariable int number)
{
Stock stock = service.findOne(number);
if(Stock ==null)
//runtime exception
throw new StockNotFoundException("number: "+ number);
return stock;
}
package com.TechTalkDebu;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.NOT_FOUND)
public class StockNotFoundException extends RuntimeException
{
public StockNotFoundException(String message)
{
super(message);
}
}
Now, you can hit the same URL again and there you go, you get a 404 error when a
resource is not found.
The latest version of spring boot is 2.6.0. It came out with a lot of dependency
upgrades, java 15 support and much more.
Yes, now as you are brushed up with spring boot interview questions and answers. We
have also tried to cover all the springboot interview questions for experienced
professionals. Hope you can easily crack the spring boot interview now!
Please feel free to comment below if you have any queries related to the above
questions or answers. Also, do comment if you find any other questions that you think
must be included in the above list of questions.
If we need to set the different target environments, Spring Boot has a built-in
mechanism.
One can simply define an application environment.properties file in the
src/main/resources directory and then set a Spring profile with the same environment
name.
For example, if we define a “production” environment, that means we’ll have to define a
production profile and then application-production.properties.
This environment file will be loaded and will take precedence over the default property
file. You should note that the default file will still be loaded. It’s just that when there is a
property collision, the environment-specific property file takes precedence.
Properties File
Properties files are used to keep one or more properties in a single file to run the
application in a different environment. Properties are kept in the application.properties
file under the classpath in a typical spring boot application. The location of the
application.properties file is at src/main/resources directory. The code of
application.properties file is as below:
sever.port=9090
spring.application.name = demoservice
YAML File
Spring Boot also supports YAML-based properties configurations to run the application.
The user can use, application.yml file instead of the application.properties file. The
YAML file is kept inside the classpath. The sample application.yml file is given below −
spring:
application:
name: demoservice
Server:
port: 9090
Externalized Properties
The user can keep properties in different locations or paths instead of keeping the
properties file under classpath. While running the JAR file, the user can specify the
properties file path. The application developer can use the following command to
specify the location of the properties file while running the JAR −
-Dspring.config.location = C:\application.properties
-C:\demo\target>java -jar -
Dspring.config.location=C:\application.properties demo-0.0.1-
SNAPSHOT.jar
42. What are the basic Annotations that spring boot offers?
First of all, we have to know about the annotations. Annotations are used to instruct the
intention of the programmers.
As the name suggests, spring boot annotations is a form of Metadata that provides the
whole data about the program. In other ways, we can define it as annotations are used
to provide supplemental information about the program. It is not part of the program.
This indicates that the annotated bean must be populated at the configuration time with
the required property; if the following case is not satisfied, it throws an exception
BeanInitializationException.
2. @Autowired:-
3. @configuartion.
4. @Componentscan
5. @Bean
6. @component.
7. @Controller.
8. @service.
9. @Repository
10. @EnableAutoConfiguaration
11. @SpringBootApplication.
12. @RequestMapping
13. @GetMapping
14. @PostMapping.
Yes, but the application could also be called as spring boot standalone application.
To create a non-web application, your application needs to implement
CommandLineRunner interface and its Run method for the running of our application.
So this run method always acts like the main of our non-web application.
45. What is the default port of the tomcat server in Spring Boot?
As we had already discussed about the default port, the tomcat server in spring boot is
port 8080. Which is changeable based on the user or the programmer’s requirement.
If we consider the fact, spring boot by default comes up with the embedded server once
we add the “Spring –boot-starter” dependency. But the spring boot gives us the
flexibility to use the tomcat.
If we don’t want to use the tomcat, then tomcat comes with three types of embed
servers: Tomcat, jetty, and undertow.
47. Can we disable the default web server in the spring boot application?
Yes, as discussed above, there are 3 web servers available we can choose between
them. Spring boot gives more priority for using the tomcat server.
@controller @RestController
50. Describe the flow of HTTPS request through the spring boot app?
We all can see the above image of the spring boot flow architecture to understand the
basic concept of the HTTPS request flow in the spring boot app.
We have the validator classes, view classes, and utility classes.
As we all know, spring boot uses the modules of spring-like MVC, spring data, etc.
So the concept also the same for several things, and also the architecture of spring boot
is the same as the architecture of spring MVC; instead of one concept, there is no need
for the DAO and DAOimpl classes in spring boot.
All the business logic performs in the service layer.Service layer performs the logic on
the data that is mapped to JPA with model classes.
A JSP page is returned to the user if no error has occurred.
52. How to get the list of all the beans in your spring boot application?
In the case of spring boot, you can use appContext.getBeanDefinitionNames() to get all
the beans loaded by the spring container.
By calling this method, we can show all of our beans present in our spring boot
applications.
Spring Cloud which builds on top of Spring Boot, provides features to quickly build
production-ready microservices. It’s possible to quickly set up services with minimal
configurations Eg. Service Registration and discovery, circuit breakers, proxies, logging,
log tracking, monitoring, etc.
For example, if a team is working on one of the microservice using Java, Spring Boot,
and MySQL, another team can work on another microservice using Python, Node JS,
and NoSQL.
Polyglot architecture where different microservices can use a different version of the
same programming language and/or different programming language and/or different
architectures as well.
a. Same code base for presentation, business layer, and data access layer. Application
is deployed as a single unit.
API Gateway can also aggregate the results from the microservices back to the client.
API Gateway can also translate between web protocols like HTTP, web socket, etc.API
Gateway can provide every client with a custom API as well.
An example of an API Gateway is Netflix API Gateway.
Microservices are developed and deployed quickly and in most cases automatically as
part of the CI/CD pipeline. Microservices could be deployed in Virtual Machines or
Containers. The virtual machines or containers can be On-premise or in the cloud as
well.
There are different deployment approaches available for Microservices. Some of the
possible deployment approaches for microservices are mentioned below.
(
"timestamp": "2020-04-02T01:31:08.501+00:00",
"path": "/shop/action",
"status": 500,
"error": "Internal Server Error",
"message": "",
"requestId": "a8c4c6d4-3"
}
Spring Cloud is an open-source library that provides tools for quickly deploying the JVM
based application on the clouds. It provides a better user experience and an extensible
mechanism due to various features like Distributed configuration, Circuit breakers,
Global locks, Service registrations, Load balancing, Cluster state, Routing, Load
Balancing, etc. It is capable of working with spring and different applications in various
languages
● Distributed configuration
● Distributed messaging
● service-to-service calls
● Circuit breakers
● Global locks
● Service registration
● Service Discovery
● Load balancing
● Cluster state
● Routing
Spring Application loads properties from the application.properties files in the following
locations and add them to the Spring Environment:
The list is ordered by precedence means that the properties that are defined in locations
higher in the list override those defined in lower locations.
If the user does not want application.properties as the configuration file name, they can
switch to another by specifying a spring.config.name environment property. The user
can also refer to an explicit location using the spring.config.location environment
property (comma-separated list of directory locations, or file paths).
<dependencies>
<dependency>
<groupID>org.springframework.security</groupID>
<artifactId>spring-security-config</artifactID>
<version>5.5.0</version>
</dependeny>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>5.5.0</version>
</dependency>
</dependencies>
repositories {
mavenCentral()
}
dependencies {
compile 'org.springframework.security:spring-security-web:5.5.0'
compile 'org.springframework.security:spring-security-config:5.5.0'}
The embedded containers supported by spring boot are Tomcat (default), Jetty, and
undertow servers
@Target(value=TYPE)
@Retention(value=RUNTIME)
@Documented
@Inherited
@BootstrapWith(value=org.springframe.boot.test.autoconfigure.web.servlet
.WebMvcTestContextBootsrapper.class)
@ExtendWidth(value=org.springframework.test.contect.junit.jupiter.Spring
Extension.class)
@AutoConfigureCache
@AutoConfigureWebMvc
@AutoConfigureMockMvc
@ImportAutoConfiguration
public @interface WebMvcTest
Annotation can be used for a Spring MVC test that focuses only on Spring MVC
components.
Using this annotation disables full auto-configuration and instead apply only
configuration relevant to MVC tests (i.e., @Controller, @ControllerAdvice,
@JsonComponent, Converter/GenericConverter, Filter, WebMvcConfigurer, and
HandlerMethodArgumentResolver beans but not @Component, @Service, or
@Repository beans).
By default, annotated tests with @WebMvcTest will also auto-configure Spring Security
and MockMvc (including support for HtmlUnit WebClient and Selenium WebDriver). For
more fine-grained control of MockMVC, the @AutoConfigureMockMvc annotation is
used.
Usually @WebMvcTest is used in combination with @MockBean or @Import to create
any collaborators required by your @Controller beans.
Spring Boot provides a LoggingSystem abstraction that configures logging based on the
content of the classpath. If Logback is available, it is definitely the first choice.
Suppose the only change the user needs to make to logging is to set the levels of
various loggers. In that case, they can do so in application.properties by using the
“logging.level” prefix, as shown in the following example:
logging.level.org.springframework.web=DEBUG
logging.level.org.hibernate=ERROR
67. What is the Minimum Java version needed for Spring Boot?
1. First, create a Spring Boot Project using STS or Spring Initializer. Add
dependency for Thymeleaf and Spring Web.
For Gradle:
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-web'
For Maven:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
DemoController.java:
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class DemoController {
@GetMapping(value = "/thymeleafTemplate")
public String getTemplate(@RequestParam(name="name" , required=false,
defaultValue="World") String name, Model model) {
model.addAttribute("name",name);
return "thymeleafTemplate";
}
}
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title> Thymeleaf Spring Boot Demo </title>
</head>
<body>
<p th:text=" 'Hello, ' + ${name} + '!'"/>
<h4> Welcome to Thymeleaf Demo in Spring Boot</h4>
</body>
</html>
4. Build code.
Run the application using Integrated Development Environment: Run as -> Spring Boot
App.
To run Spring Boot for Command-Line Applications, Open the terminal window and
change the directory to the root folder of your Spring Boot application.
If the user list files in this directory, they should see a pom.xml file. One can also run
your Spring Boot application as an executable Java jar file
70. How Can You Change the Default Port in Spring Boot?
Default port is 8080; The user can change the default port by:
@SpringBootApplication
public class CustomApplication {
public static void main(String[] args {
SpringApplication app = new SpringApplication(CustomApplication.class);
app.setDefaultProperties(Collection.singletonMap("server.port",
"8083"));
app.run(args);
}
If you are using Eclipse IDE or an Eclipse maven plugin, make sure that as soon as you
add a dependency or change the class file, it is compiled and available in the target
folder. After that, it is just like any other Java application.
When you launch the java application, then the spring boot auto configuration kicks in.
It starts up tomcat when it sees that you are developing a web application!
Manager is used. The query language in Hibernate is Hibernate Query language, while
in JPA, the query language is Java Persistence query language. Hibernate is one of the
most JPA providers.
The @ComponentScan annotation is used to scan the components added to the project
for the class file. It is also used to specify base packages and their classes using the
basePackages attributes. As you specify the basePackages attribute, this will prompt
Spring Boot to scan all the packages as well as subpackages of the classes that have
been specified.
Spring initializr is a web-based application that helps in generating spring boot projects
for developers. It will provide the basic structure code without any application code.
Using the Maven or a Gradle build specification, you can build the code. It is very
helpful when you are starting a project from scratch as it eliminates the need for setting
up a framework.
77. What are the HTTP methods that can be implemented in spring boot
rest service?
Here are the essential HTTP methods that can be implemented in the spring boot rest
service –
✓ GET: A key HTTP method, GET is used to know the representational view of the
data. When used in read-only mode, it helps in keeping the data safe and secure.
Also, the results are idempotent which means that you will get the same results
no matter how many times it is used.
✓ POST: The POST restful API HTTP method works on resource collections. Using
POST on the parent resource creates new resources associated with a proper
hierarchy. It is highly useful for developers to prevent polluting the code and
define resources in an explicit manner.
✓ PUT: The PUT restful API helps in updating a resource. It does so by replacing
the content of that resource entirely. It is the most common way of updating
information.
✓ PATCH: PATCH is also used to update resources. Unlike the PUT method, it
only modifies resource content and does not replace it entirely. Unless you want
to update every resource of your content, it is poor practice to apply PATCH.
✓ DELETE: This HTTP method is used to target and delete a single resource.
However, its implementation can be inconsistent sometimes.
78. What are the steps to add a custom JS code with Spring Boot?
You can add a custom JS code with Spring Boot in these steps –
Spring Boot provides a good platform for Java developers to reduce overall
development time and increase efficiency by integrating tests. One can choose Spring
Boot because it provides powerful batch processing, eases dependency management,
and no manual configurations are needed.
The main class in spring boot is configured automatically by the “public static void
main()” method that starts up the Spring ApplicationContext.
Eureka service can discover dependent microservices in spring boot to get the job
done. This service will register all the client microservices through the eureka server to
get the dependent microservice.
In Spring, the bean is defined as an object that is like a backbone of your application,
managed by a Spring IoC container.
Classpath in spring boot is defined as a path where you place resources. During the
development, stage maven will take files and place them in the appropriate place for
you to use them.