[ad_1]
While Spring Boot, microservices are the high rated technologies/frameworks in software industry, and it is one of the most used technology with Java to create web applications. you must have wondered about getting in and learning all the in and outs of those frameworks and going through the questionnaires’ that are being asked during the interviews.
Yes, you are in the right place. Here, in this article, we have listed all the latest and most frequently asked questions based on Spring Boot with proper explanation and examples that also helps you understand the overall concept from the base.
You can also use the code provided for some of the questions and run it on your machines to get better clarity on the concepts.
In this article, you can go through these questions and attend any interview based on Spring Boot and your interview will definitely be cracked. Below questions are little tricky, and trending but have explained it in a very simple and understandable way and you may find it very easy as you read it further.
1. What is spring boot?
∙ Spring Boot is basically, a microservice framework that is built on top of the spring framework.
∙ Spring boot helps developers to focus more on convention rather than configuration as all the basic configuration will be handled by spring boot.
∙ 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.
∙ It comes with features like autoconfiguration, auto dependency resolution, embedded servers, security, health checks which enhances the productivity of a developer.
2. How to create spring-boot project in eclipse?
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!
3. How to deploy spring boot application in tomcat?
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.
4. What is the difference between spring and spring boot?
Difference between Spring and Spring boot are as follows:
Spring –
∙ Is a dependency injection framework.
∙ It is basically used to manage the life cycle of java classes (beans). It consists of a lot of boilerplate configuration.
∙ Uses XML based configuration.
∙ It takes time to have a spring application up and running and it’s mainly because of boilerplate code.
Spring boot-
∙ It is a suite of pre- configured frameworks and technologies which helps to remove boilerplate configuration.
∙ Uses annotations.
∙ It is used to create a production-ready code.
5. What is actuator in spring boot?
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.
6. How to change port in spring boot?The default port number to start your springBoot application is 8080.
Just to change the port number, you need to add server.port=8084(your port number) property in your application.properties file and start your application.
7. How to install spring boot in eclipse?
The classic and preferred way to install STS in eclipse is,
Go to Eclipse IDE, click on “Help”->then go to Eclipse marketplace->and type Spring IDE and click on finish button.
8. How to create war file in spring boot?
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.
9. What is JPA in spring boot?
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.
10. How to save image in database using spring boot?
∙ First configure mysql in your spring boot application.
∙ 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
1. .
2.
@RestController
3. @RequestMapping(“/greatleasrning”)
4. public class Controller {
5.
6. @Autowired
7. private final GreatLearningRepository greatLearningRepository;
8.
9. public Controller(GreatLearningRepository greatLearningRepository) {
10. this. greatLearningRepository = greatLearningRepository;
11. }
In above case, your data which may be in JSON format can be inserted successfully into database.
12. @RequestMapping(method = RequestMethod.POST)
13. ResponseEntity<?> insert(@RequestBody Course course) {
14. greatLearningRepository.save(course);
15. return ResponseEntity.accepted().build();
16.
17. }
}
11. What is auto configuration in spring boot?
AutoConfiguration is a process by which Spring Boot automatically configures all the infrastructural beans. It declares the built-in beans/objects of the spring specific module such as JPA, spring security and so on based on the dependencies present in your applications class path.
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.
12. How to change port number in spring boot?
The default port number to start your Spring Boot application is 8080.
Just to change the port number, you need to add server.port=8084(your port number) property in your application.properties file and start your application.
13. How to resolve whitelabel error page in spring boot application?
This is quite common error in spring boot application which says 404(page not found).
We can mostly resolve this in 3 ways:
1) Custom Error Controller– where you will be implementing ErrorController interface which is provided by SpringFramework and then overriding its getErrorPath() so that you can return a custom path whenever such type of error is occurred.
2) By Displaying Custom error page– All you have to do is create an error.html page and place it into the src/main/resources/templates path. The BasicErrorController of of springboot will automatically pick this file by default.
3)By disabling the whitelabel error page– this is the easiest way where all you need to do is server.error.whitelabel.enabled property to false in the application.properties file to disable the whitelabel error page.
14. How to fetch data from database in spring boot?
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.
18. spring.datasource.url=jdbc:mysql://localhost:3306/studentDetails
19. spring.datasource.username=system123
20. spring.datasource.password=system123
21. spring.jpa.hibernate.ddl-auto=create-drop
5) In your controller class,you need to handle the requests.
22. package com.student;
23. import org.springframework.web.bind.annotation.RequestMapping;
24. import org.springframework.beans.factory.annotation.Autowired;
25. import org.springframework.jdbc.core.JdbcTemplate;
26. import org.springframework.web.bind.annotation.RestController;
27. @RestController
28.
29. public class JdbcController {
30. @Autowired
31. JdbcTemplate jdbc;
32. @RequestMapping(“/save”)
33. public String index(){
34. jdbc.execute(“insert into student (name)values(GreatLearnings)”);
35. return “Data Entry Successful”;
36. }
37. }
6) Run the application and check the entry in your Database.
15. What is response entity in spring boot?
Response Entity is basically an HTTP response which includes headers,status code and body of your response.
16. How to use logger in spring boot?
There are many logging options available in springboot.
Some of them are mentioned below:
1. Using log4j2:
For this, we have to only use the native classes.
38. import org.apache.logging.log4j.Logger;
39. import org.apache.logging.log4j.LogManager;
40. // […]
- Logger logger = LogManager.getLogger(LoggingController.class);
2. Using Lombok:
All you need to do is add a dependency called org.projectlombok in your pom.xml as shown below:
42. <dependency>
43. <groupId>org.projectlombok</groupId>
44. <artifactId>lombok</artifactId>
45. <version>1.18.4</version>
46. <scope>provided</scope>
47. </dependency>
Now you can create a loggingController and add the @Slf4j annotation to it. Here we would not create any logger instances.
48. @RestController
49. @Slf4j
50. public class LoggingController {
51.
52. @RequestMapping(“/logging”)
53. public String index() {
54. log.trace(“A TRACE Message”);
55. log.debug(“A DEBUG Message”);
56. log.info(“An INFO Message”);
57. log.warn(“A WARN Message”);
58. log.error(“An ERROR Message”);
59.
60. return “Here are your logs!”;
61. }
62. }
So, there are many such ways in spring boot to use logger.
17. What is bootstrapping in spring boot?
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.
18. Spring boot introduced in which year?
Spring boot was introduced in the year 2002.
19. How to create jar file in spring boot?
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.
20. How to handle exceptions in spring boot?
To handle exceptions in spring boot, you can use @ControllerAdvice annotation to handle your exceptions globally.
In order to handle specific exception and send customized response, you need to use @ExceptionHandler annotation.
21. What is dependency injection in spring boot?
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.
22. How to store image in mongodb using spring boot?
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.
63. <dependency>
64. <groupId>com.github.paulcwarren</groupId>
65. <artifactId>spring-content-mongo-boot-starter</artifactId>
66. <version>0.0.10</version>
67. </dependency>
You should have a GridFsTemplate bean in your applicationContext.
68. @Configuration
69. public class Config
70.
71. @Bean
72. public GridFsTemplate gridFsTemplate() throws Exception {
73. return new GridFsTemplate(mongoDbFactory(), mappingMongoConverter());
74. }
75. …
Now add attributes so that youe content will be associated to your entity.
76. @ContentId
77. private String contentId;
78.
79. @ContentLength
80. private long contentLength = 0L;
81.
82. @MimeType
83. private String mimeType = “text/plain”;
84. And last but not the least, add a store interface.
@StoreRestResource(path=”greatlearningImages”)
85. public interface GreatLearningImageStore extends ContentStore<Candidate, String> {
86. }
That’s all you have to do to store your images in mongoDb using Springboot.
23. Which is the ui web framework that is built to use spring boot?
The best UI web framework that can be used with springboot is JHipster.
With this you can generate your web-applications and microservices within less time.
24. How to configure hibernate in spring boot?
The important and required dependency to configure hibernate is
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
87. spring.datasource.url=jdbc:h2:file:~/test
88. spring.datasource.driverClassName=org.h2.Driver
89. spring.datasource.username=test
90. spring.datasource.password=test
91. spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
92. spring.h2.console.enabled=true
93. 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.
25. Why spring boot is used for microservices?
In microservices, you can write code for your single functionality. You can use different technology stacks for different microservices as per the skill set.
You can develop this type of microservices with the help of Spring boot very quickly as spring boot gives priority to convention over configuration which increases the productivity of your developers.
26. Mention the advantages of Spring Boot.
Advantages of Spring Boot-
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.
27. Explain Spring Actuator and its advantages.
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 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.
28. Explain what is thyme leaf and how to use thymeleaf?
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.
29. What is the need for Spring Boot DevTools?
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.
30. 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
31. Mention the steps to connect Spring Boot application to a database using JDBC
Below are the steps to connect your Spring Boot application to a database using JDBC:
Before that, you need to add required dependencies that are provided by spring-boot to connect your application with JDBC.
Step 1: First create a database in MySQL with create DATABASE student;
94. Step 2: Now, create a table inside this DB:
CREATE TABLE student(studentid INT PRIMARY KEY NOT NULL AUTO_INCREMENT,
95. studentname VARCHAR(255));
Step 3: Create a springBoot and add JDBC,mysql and web
dependencies.
Step 4: In application.properties, you need to configure the database.
96. spring.datasource.url=jdbc:mysql://localhost:3306/studentDetails
97. spring.datasource.username=system123
98. spring.datasource.password=system123
99. spring.jpa.hibernate.ddl-auto=create-drop
Step 5: In your controller class, you need to handle the requests.
100.package com.student;
101.import org.springframework.web.bind.annotation.RequestMapping;
102. import org.springframework.beans.factory.annotation.Autowired;
103. import org.springframework.jdbc.core.JdbcTemplate;
104. import org.springframework.web.bind.annotation.RestController;
105. @RestController
106. public class JdbcController {
107. @Autowired
108. JdbcTemplate jdbc;
109. @RequestMapping(“/save”)
110. public String index(){
111. jdbc.execute(“insert into student (name)values(GreatLearnings)”);
112. return “Data Entry Successful”;
113. }
114. }
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.
32. What are the @RequestMapping and @RestController annotation in Spring Boot used for?
∙ The @RequestMapping annotation can be used at class-level or method level in your controller class.
∙ 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.
Below is a simple example to refer to:
115.@RestController
116.@RequestMapping(“/greatLearning”)
117.public class GreatLearningController {
118.@RequestMapping(“/”)
119.String greatLearning(){
120.return “Hello from greatLearning “;
121.}
122.@RequestMapping(“/welcome”)
123. String welcome(){
124.return “Welcome from GreatLearning”;
125. }
126.}
∙ The @RestController annotation is used at the class level.
∙ You can use @RestController when you need to use that class as a request handler class.All the requests can be mapped and handled in this class.
∙ @RestController itself consists @Controller and @ResponseBody which helps us to remove the need of annotating every method with @ResponseBody annotation.
Below is a simple example to refer to for use of @RestController annotation:
127.@RestController
128.@RequestMapping(“bank-details”)
129.public class DemoRestController{
130.@GetMapping(“/{id}”,produces =”application/json”)
131.public Bank getBankDetails(@PathVariable int id){
132. return findBankDetailsById();
133.}
134.}
Here, @ResponseBody is not required as the class is annotated with @RestController.
33. How can we create a custom endpoint in Spring Boot Actuator?
By using @Endpoint annotation, you can create a custom endpoint.
34) What do you understand by auto-configuration in Spring Boot and how to disable the auto-configuration?
AutoConfiguration is a process by which Spring Boot automatically configures all the infrastructural beans. It declares the built-in beans/objects of the spring-specific module such as JPA, spring-security, and so on based on the dependencies present in your application’s classpath.
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 explicitly is called Autoconfiguration which is done by spring-boot with the help of an annotation called @EnableAutoconfiguration alternatively @SpringBootApplication.
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:
135. spring.autoconfigure.exclude= org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,
50.org.springframework.boot.autoconfigure.data.MongoDataConfiguration,
In the above example, we have disabled the autoconfiguration of MongoDB.
35. Can you give an example for ReadOnly as true in Transaction management?
Yes, example for ReadOnly as true in Transaction Management is :
Suppose you have a scenario where you have to read data from your database like if you have a STUDENT database and you have to read the student details such as studentID, and studentName.
So in such scenarios, you will have to set read-only on the transaction.
36. Mention the advantages of the YAML file than Properties file and the different ways to load
YAML file in Spring boot.
-YAML gives you more clarity and is very friendly to humans. It also supports maps, lists, and other scalar types.
YAML comes with hierarchical nature which helps in avoiding repetition as well as indentations.
If we have different deployment profiles such as development, testing, or production and we may have different configurations for each environment, so instead of creating new files for each environment we can place them in a single YAML file.
But in the case of the properties file, you cannot do that.
For example:
136.spring:
137. profiles:
138. active:
139. -test
140.—
141.
142.spring:
143. profiles:
144. active:
145. -prod
146.—
147.spring:
148. profiles:
149. active:
150. -development
37. What do you understand by Spring Data REST?
By using Spring Data Rest, you have access to all the RESTful resources that revolves around Spring Data repositories.
Refer the below example:
151.@RepositoryRestResource(collectionResourceRel = “greatlearning”, path = “sample”)
152.public interface GreatLearningRepo extends CustomerRepository< greatlearning, Long> {
153.
154.}
Now you can use the POST method in the below manner:
155.{
156.“Name”:”GreatLearning”
157.}
And you will get response as follow:
158.{
159.”name”: “Hello greatlearning “
160.”_links”: {
161.”self”: {
162.”href”: “<a href=”http://localhost:8080/sample/1”>http://localhost:8080/ greatlearning /1</a>”
163.},
164.” greatlearning “: {
165.“href”: “<a href=”http://localhost:8080/sample/1”>http://localhost:8080/ greatlearning /1</a>”
166.}
167.}
In the above, you can see the response of the newly created resource.
38. How do you Configure Log4j for logging?
Spring Boot supports log4j2 for logging configuration. what all you have to do is you have to exclude log backfile and include log4j2 for logging.
You can do it by using the spring starter projects.
39. What do you think is the need for Profiles?
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.
40. What are the steps to add a custom JS code with Spring Boot?
All you have to do is just create a static folder under src/main/resources and place all your static content in this folder.
And your custom JS code will be added with spring boot.
41. What is the name of the default H2 database configured by Spring Boot?
H2 database is an in-memory database configured by SpringBoot.
The default name of the H2 database that is configured by spring boot is testdb.
42. How to call servlet in spring boot?
Servlet can be configured by using implementing or extending WebAppInitializer interface,AbstractDispatcherServletInitializer abstract class, and AbstractAnnotationConfigDispatcherServletInitializer abstract class
43. what is the HTTP methods that can be implemented in spring boot rest service?
Spring boot rest service helps in CRUD (create,retrieve,update,delete)operations. So based on that most commonly used HTTP methods are GET, POST, PUT, DELETE, and PATCH are the methods that can be implemented in spring boot rest services.
44. How to debug spring boot application in eclipse?
Debugging your spring boot application is as simple as same as debugging your Java application.
All you have to do is place debug point within your application, and right-click-> click on debug as java application or spring boot application.
45. How to insert data in mysql using spring boot?
First configure mysql in your spring boot application.
Then you can map your entities with your db tables using JPA.
168. And with the help of save() method in JPA, you can directly insert your data into your database.
169.
@RestController
170.@RequestMapping(“/greatleasrning”)
171.public class Controller {
172.
173. @Autowired
174. private final GreatLearningRepository greatLearningRepository;
175.
176. public Controller(GreatLearningRepository greatLearningRepository) {
177. this. greatLearningRepository = greatLearningRepository;
178. }
In the above case, your data which may be in JSON format can be inserted successfully into the database.
179. @RequestMapping(method = RequestMethod.POST)
180. ResponseEntity<?> insert(@RequestBody Course course) {
181. greatLearningRepository.save(course);
182. return ResponseEntity.accepted().build();
183.
184. }
}
46. How to create a login page in spring boot?
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.
47. What is the main class in spring boot?
Usually in java applications, a class that has a main method in it is considered as a main class. Similarly, in spring boot applications main class is the class which has a public static void main() method and which starts up the SpringApplicationContext.
48. How to use crud repository in spring boot?
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
And extend your repository interface as shown below:
package com.greatlearning;
185.import java.util.List;
186.import org.springframework.data.repository.CrudRepository;
187.import org.springframework.data.rest.core.annotation.RepositoryRestResource;
188. @RepositoryRestResource
190.public interface GreatLearning extends CrudRepository<Candidate, Long>
191.{
192. public List<Candidate> findById(long id);
193.
194. //@Query(“select s from Candidate s where s.age <= ?”)
195. public List<Candidate> findByAgeLessThanEqual (long age);
196.}
49. How to run spring-boot jar from the command line?
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>
197.<plugins>
198.<plugin>
199.<groupId>org.springframework.boot</groupId>
200.<artifactId>spring-boot-maven-plugin</artifactId>
201.</plugin>
202.</plugins>
203. </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:
java -jar target/myDemoService-0.0.1-SNAPSHOT.jar
And you have your application running.
50. 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;
51. How to ignore null values in JSON response spring boot?
In order to ignore null values in JSON response, you can use @JsonIgnore annotation.
The field can be ignored while reading JSON into Java objects as well as while writing Java objects into JSON.
52. what is the rest controller in spring boot?
∙ The @RestController annotation is used at the class level.
∙ You can use @RestController when you need to use that class as a request handler class.All the requests can be mapped and handled in this class.
∙ @RestController itself consists @Controller and @ResponseBody which helps us to remove the need of annotating every method with @ResponseBody annotation.
Below is a simple example to refer to for use of @RestController annotation:
1. @RestController
2. @RequestMapping(“bank-details”)
3. public class DemoRestController{
4. @GetMapping(“/{id}”,produces =”application/json”)
5. public Bank getBankDetails(@PathVariable int id){
6. return findBankDetailsById();
7. }
8. }
Here, @ResponseBody is not required as the class is annotated with @RestController.
53. How to handle 404 error in spring boot?
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”.
9. GetMapping(“/stocks/{number}”)
10. public Stock retriveStock(@PathVariable int number)
11. {
12. Stock stock = service.findOne(number);
13. if(Stock ==null)
14. //runtime exception
15. throw new StockNotFoundException(“number: “+ number);
16. return stock;
17. }
18.
Now, create a Constructor from Superclass.
Right-click on the file -> Go to Source ->And generate constuctors from superclass-> and check the RuntimeException(String)-> and generate.
And add an annotation called @ResponseStatus which will give you 404(not found) error.
19. package com.greatlearning;
20. import org.springframework.http.HttpStatus;
21. import org.springframework.web.bind.annotation.ResponseStatus;
22.
23. @ResponseStatus(HttpStatus.NOT_FOUND)
24. public class StockNotFoundException extends RuntimeException
25. {
26. public StockNotFoundException(String message)
23.{
27. super(message);
28. }
29. }
30.
Now, you can hit the same URL again and there you go, you get a 404 error when a resource is not found.
54. How to do pagination in spring boot?
The process of dividing your data into small and suitable chunks is Pagination.
One can achieve pagination by using PagingAndSortingRepository which is an extension of crudRepository.
Yes, now as you are ready for cracking the Spring boot interview, 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.
For a more detailed course experience, visit Great Learning Academy, where you will find a bunch of free courses on AIML and Data Science.
All The Best!
0
[ad_2]
Source link