└── README.md
/README.md:
--------------------------------------------------------------------------------
1 | # Java Spring Boot Interview Questions and Answers
2 |
3 | ### Table of Contents
4 |
5 |
6 |
7 | Hide/Show table of contents
8 |
9 |
10 | | No. | Questions |
11 | | --- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
12 | | | **Basic Questions** |
13 | | 1 | [What is Spring Boot?](#what-is-spring-boot) |
14 | | 2 | [What are the advantages of Spring Boot?](#what-are-the-advantages-of-spring-boot) |
15 | | 3 | [What are the main features of Spring Boot?](#what-are-the-main-features-of-spring-boot) |
16 | | 4 | [What are the differences between Spring and Spring Boot?](#what-are-the-differences-between-spring-and-spring-boot) |
17 | | 5 | [How does Spring Boot simplify development?](#how-does-spring-boot-simplify-development) |
18 | | 6 | [How to create a Spring Boot application using Maven?](#how-to-create-a-spring-boot-application-using-maven) |
19 | | 7 | [How to create a Spring Boot project using Spring Initializer?](#how-to-create-a-spring-boot-project-using-spring-initializer) |
20 | | 8 | [How do you create a simple Spring Boot application?](#how-do-you-create-a-simple-spring-boot-application) |
21 | | 9 | [What are Spring Boot Starters?](#what-are-spring-boot-starters) |
22 | | 10 | [What is the use of the @SpringBootApplication annotation?](#what-is-the-use-of-the-springbootapplication-annotation) |
23 | | 11 | [What is the Spring Initializr?](#what-is-the-spring-initializr) |
24 | | 12 | [What are the Spring Boot annotations?](#what-are-the-spring-boot-annotations) |
25 | | 13 | [What is Spring Boot dependency management?](#what-is-spring-boot-dependency-management) |
26 | | 14 | [What are the Spring Boot properties?](#what-are-the-spring-boot-properties) |
27 | | 15 | [What are Spring Boot starters?](#what-are-spring-boot-starters) |
28 | | 16 | [What is Spring Boot Actuator?](#what-is-spring-boot-actuator) |
29 | | 17 | [How to connect Spring Boot to the database using JPA?](#how-to-connect-spring-boot-to-the-database-using-jpa) |
30 | | 18 | [How to connect Spring Boot application to a database using JDBC?](#how-to-connect-spring-boot-application-to-a-database-using-jdbc) |
31 | | 19 | [What is @RestController annotation in Spring Boot?](#what-is-restcontroller-annotation-in-spring-boot) |
32 | | 20 | [What is @RequestMapping annotation in Spring Boot?](#what-is-requestmapping-annotation-in-spring-boot) |
33 | | 21 | [How does Spring Boot simplify dependency management?](#how-does-spring-boot-simplify-dependency-management) |
34 | | 22 | [What is the role of embedded servers in Spring Boot?](#what-is-the-role-of-embedded-servers-in-spring-boot) |
35 | | 23 | [What are Profiles in Spring Boot?](#what-are-profiles-in-spring-boot) |
36 | | | **Intermediate Questions** |
37 | | 1 | [What are the basic Spring Boot annotations?](#what-are-the-basic-spring-boot-annotations) |
38 | | 2 | [Is it possible to change the port of the embedded Tomcat server in Spring Boot?](#is-it-possible-to-change-the-port-of-the-embedded-tomcat-server-in-spring-boot) |
39 | | 3 | [What is the starter dependency of the Spring Boot module?](#what-is-the-starter-dependency-of-the-spring-boot-module) |
40 | | 4 | [What is the default port of Tomcat in Spring Boot?](#what-is-the-default-port-of-tomcat-in-spring-boot) |
41 | | 5 | [Can we disable the default web server in the Spring Boot application?](#can-we-disable-the-default-web-server-in-the-spring-boot-application) |
42 | | 6 | [How to disable a specific auto-configuration class?](#how-to-disable-a-specific-auto-configuration-class) |
43 | | 7 | [Can we create a non-web application in Spring Boot?](#can-we-create-a-non-web-application-in-spring-boot) |
44 | | 8 | [Explain @RestController annotation in Spring Boot.](#explain-restcontroller-annotation-in-spring-boot) |
45 | | 9 | [Difference between @Controller and @RestController?](#difference-between-controller-and-restcontroller) |
46 | | 10 | [What is the difference between RequestMapping and GetMapping?](#what-is-the-difference-between-requestmapping-and-getmapping) |
47 | | 11 | [What are Profiles in Spring Boot?](#what-are-profiles-in-spring-boot) |
48 | | 12 | [How do you enable Actuator in the Spring Boot application?](#how-do-you-enable-actuator-in-the-spring-boot-application) |
49 | | 13 | [How do you handle exceptions in a Spring Boot application?](#how-do-you-handle-exceptions-in-a-spring-boot-application) |
50 | | 14 | [What is Swagger in Spring Boot?](#what-is-swagger-in-spring-boot) |
51 | | 15 | [How do you implement security in a Spring Boot application?](#how-do-you-implement-security-in-a-spring-boot-application) |
52 | | 16 | [What are the different ways to configure Spring Boot applications?](#what-are-the-different-ways-to-configure-spring-boot-applications) |
53 | | 17 | [What is Spring Data JPA, and how does it differ from Hibernate?](#what-is-spring-data-jpa-and-how-does-it-differ-from-hibernate) |
54 | | 18 | [How do you use Spring Boot with Docker?](#how-do-you-use-spring-boot-with-docker) |
55 | | 19 | [What is the difference between @Component, @Service, and @Repository annotations?](#what-is-the-difference-between-component-service-and-repository-annotations) |
56 | | 20 | [How do you test RESTful services in Spring Boot?](#how-do-you-test-restful-services-in-spring-boot) |
57 | | 21 | [How do you configure multiple data sources in Spring Boot?](#how-do-you-configure-multiple-data-sources-in-spring-boot) |
58 | | 22 | [What is the role of the Spring Boot Actuator?](#what-is-the-role-of-the-spring-boot-actuator) |
59 | | 23 | [How do you integrate Kafka with Spring Boot?](#how-do-you-integrate-kafka-with-spring-boot) |
60 | | | **Advanced Questions** |
61 | | 1 | [What are the annotations used to create an Interceptor in Spring Boot?](#what-are-the-annotations-used-to-create-an-interceptor-in-spring-boot) |
62 | | 2 | [What is the purpose of Swagger in Spring Boot?](#what-is-the-purpose-of-swagger-in-spring-boot) |
63 | | 3 | [What are the differences between Spring Data JPA and Hibernate?](#what-are-the-differences-between-spring-data-jpa-and-hibernate) |
64 | | 4 | [How do you use Spring Boot with Docker?](#how-do-you-use-spring-boot-with-docker) |
65 | | 5 | [How to implement caching in Spring Boot?](#how-to-implement-caching-in-spring-boot) |
66 | | 6 | [How to configure Spring Boot for asynchronous processing?](#how-to-configure-spring-boot-for-asynchronous-processing) |
67 | | 7 | [How do you configure multiple data sources in Spring Boot?](#how-do-you-configure-multiple-data-sources-in-spring-boot) |
68 | | 8 | [What is the purpose of @ComponentScan in the class files?](#what-is-the-purpose-of-componentscan-in-the-class-files) |
69 | | 9 | [How to monitor a Spring Boot application using Actuator?](#how-to-monitor-a-spring-boot-application-using-actuator) |
70 | | 10 | [How do you implement distributed tracing in a Spring Boot application using OpenTelemetry?](#how-do-you-implement-distributed-tracing-in-a-spring-boot-application-using-opentelemetry) |
71 | | 11 | [How do you enable HTTPS in a Spring Boot application?](#how-do-you-enable-https-in-a-spring-boot-application) |
72 | | 12 | [How to configure custom health checks in Spring Boot Actuator?](#how-to-configure-custom-health-checks-in-spring-boot-actuator) |
73 | | 13 | [How to configure Spring Boot to send and receive messages from an external messaging system like RabbitMQ?](#how-to-configure-spring-boot-to-send-and-receive-messages-from-an-external-messaging-system-like-rabbitmq) |
74 |
75 |
76 |
77 | ## Core Spring Boot
78 | 1. ### What is Spring Boot?
79 |
80 | Spring Boot is an **open-source framework** built on top of the Spring Framework that simplifies the development of Java-based applications. It is designed to make it easier to create stand-alone, production-grade Spring-based applications with minimal configuration.
81 |
82 | **[⬆ Back to Top](#table-of-contents)**
83 |
84 | 2. ### What are the advantages of Spring Boot?
85 |
86 | The main advantages of Spring Boot include:
87 |
88 | - **Auto-configuration**: Automatically configures Spring and third-party libraries based on project dependencies.
89 | - **Standalone**: Spring Boot applications can run as standalone Java applications.
90 | - **Production-ready**: Includes features like metrics, health checks, and externalized configuration.
91 | - **Microservice-ready**: Ideal for building microservices due to its lightweight and modular design.
92 |
93 | **[⬆ Back to Top](#table-of-contents)**
94 |
95 | 3. ### What are the main features of Spring Boot?
96 |
97 | Major features of Spring Boot are:
98 |
99 | - **Auto-configuration**: Automatically configures your Spring application based on the dependencies you have added.
100 | - **Standalone**: Spring Boot applications can be run from the command line.
101 | - **Production-ready**: Includes built-in features for monitoring and managing your application.
102 | - **Microservices**: Facilitates building microservices with minimal configuration.
103 |
104 | **[⬆ Back to Top](#table-of-contents)**
105 |
106 | 4. ### What are the differences between Spring and Spring Boot?
107 |
108 | - **Configuration**: Spring requires extensive XML configuration or Java-based configuration. Spring Boot offers auto-configuration and minimal setup.
109 | - **Setup**: Spring projects typically need manual setup and configuration, while Spring Boot provides default configurations and embedded servers.
110 | - **Dependencies**: Spring Boot includes a variety of dependencies and auto-configuration out of the box, reducing the need for manual dependency management.
111 |
112 | **[⬆ Back to Top](#table-of-contents)**
113 |
114 | 5. ### How does Spring Boot simplify development?
115 |
116 | Spring Boot simplifies development by:
117 |
118 | - **Reducing Configuration**: Provides default configurations and auto-configuration options.
119 | - **Embedded Servers**: Includes embedded servers like Tomcat, Jetty, or Undertow, eliminating the need for external server setup.
120 | - **Spring Boot Starter Projects**: Offers pre-configured dependency sets for common tasks.
121 |
122 | **[⬆ Back to Top](#table-of-contents)**
123 |
124 | 6. ### How to create a Spring Boot application using Maven?
125 |
126 | To create a Spring Boot application using Maven, follow these steps:
127 |
128 | 1. Add the Spring Boot dependencies to your `pom.xml`:
129 |
130 | ```xml
131 |
132 | org.springframework.boot
133 | spring-boot-starter
134 |
135 | ```
136 |
137 | 2. Create the main application class with `@SpringBootApplication` annotation:
138 |
139 | ```java
140 | import org.springframework.boot.SpringApplication;
141 | import org.springframework.boot.autoconfigure.SpringBootApplication;
142 |
143 | @SpringBootApplication
144 | public class Application {
145 | public static void main(String[] args) {
146 | SpringApplication.run(Application.class, args);
147 | }
148 | }
149 | ```
150 |
151 | 3. Run your application using Maven:
152 |
153 | ```bash
154 | mvn spring-boot:run
155 | ```
156 |
157 | **[⬆ Back to Top](#table-of-contents)**
158 |
159 | 7. ### How to create a Spring Boot project using Spring Initializer?
160 |
161 | To create a Spring Boot project using Spring Initializr:
162 |
163 | 1. Visit [Spring Initializr](https://start.spring.io/).
164 | 2. Choose the project metadata (e.g., Project, Language, Spring Boot version).
165 | 3. Add dependencies.
166 | 4. Click "Generate" to download a ZIP file containing your Spring Boot project.
167 |
168 | **[⬆ Back to Top](#table-of-contents)**
169 |
170 | 8. ### How do you create a simple Spring Boot application?
171 |
172 | To create a simple Spring Boot application:
173 |
174 | 1. Create a new Maven project and add Spring Boot dependencies.
175 | 2. Create a main application class with `@SpringBootApplication`.
176 |
177 | ```java
178 | import org.springframework.boot.SpringApplication;
179 | import org.springframework.boot.autoconfigure.SpringBootApplication;
180 |
181 | @SpringBootApplication
182 | public class Application {
183 | public static void main(String[] args) {
184 | SpringApplication.run(Application.class, args);
185 | }
186 | }
187 | ```
188 |
189 | 3. Create a REST controller:
190 |
191 | ```java
192 | import org.springframework.web.bind.annotation.GetMapping;
193 | import org.springframework.web.bind.annotation.RequestMapping;
194 | import org.springframework.web.bind.annotation.RestController;
195 |
196 | @RestController
197 | @RequestMapping("/api")
198 | public class HelloController {
199 | @GetMapping("/hello")
200 | public String sayHello() {
201 | return "Hello, Spring Boot!";
202 | }
203 | }
204 | ```
205 |
206 | **[⬆ Back to Top](#table-of-contents)**
207 |
208 | 9. ### What are Spring Boot Starters?
209 |
210 | Spring Boot Starters are a set of convenient dependency descriptors you can include in your application. They simplify the process of adding commonly used dependencies.
211 |
212 | Example of including a Spring Boot Starter in `pom.xml`:
213 |
214 | ```xml
215 |
216 | org.springframework.boot
217 | spring-boot-starter-web
218 |
219 | ```
220 |
221 | **[⬆ Back to Top](#table-of-contents)**
222 |
223 | 10. ### What is the use of the @SpringBootApplication annotation?
224 |
225 | The `@SpringBootApplication` annotation is used to mark the main class of a Spring Boot application. It combines the following annotations:
226 |
227 | - `@Configuration`
228 | - `@EnableAutoConfiguration`
229 | - `@ComponentScan`
230 |
231 | It enables auto-configuration and component scanning.
232 |
233 | **[⬆ Back to Top](#table-of-contents)**
234 |
235 | 11. ### What is the Spring Initializr?
236 |
237 | The Spring Initializr is an online tool that helps generate a Spring Boot project with the desired configuration and dependencies. You can access it at [start.spring.io](https://start.spring.io/).
238 |
239 | **[⬆ Back to Top](#table-of-contents)**
240 |
241 | 12. ### What are the Spring Boot annotations?
242 |
243 | Key Spring Boot annotations include:
244 |
245 | - `@SpringBootApplication`
246 | - `@RestController`
247 | - `@RequestMapping`
248 | - `@Service`
249 | - `@Repository`
250 | - `@Configuration`
251 |
252 | **[⬆ Back to Top](#table-of-contents)**
253 |
254 | 13. ### What is Spring Boot dependency management?
255 |
256 | Spring Boot manages dependencies by providing default versions and configurations for commonly used libraries through its starter dependencies. It helps avoid version conflicts and simplifies dependency management.
257 |
258 | **[⬆ Back to Top](#table-of-contents)**
259 |
260 | 14. ### What are the Spring Boot properties?
261 |
262 | Spring Boot properties are configuration settings that can be defined in `application.properties` or `application.yml` files to customize the behavior of your application.
263 |
264 | Example of `application.properties`:
265 |
266 | ```properties
267 | server.port=8081
268 | spring.datasource.url=jdbc:mysql://localhost:3306/mydb
269 | ```
270 |
271 | **[⬆ Back to Top](#table-of-contents)**
272 |
273 | 15. ### What are Spring Boot starters?
274 |
275 | Spring Boot starters are pre-configured dependency sets for common application needs. They simplify dependency management by grouping related dependencies into a single artifact.
276 |
277 | **[⬆ Back to Top](#table-of-contents)**
278 |
279 | 16. ### What is Spring Boot Actuator?
280 |
281 | Spring Boot Actuator provides production-ready features such as monitoring, metrics, and health checks. It helps in managing and monitoring your application in production environments.
282 |
283 | **[⬆ Back to Top](#table-of-contents)**
284 |
285 | 17. ### How to connect Spring Boot to the database using JPA?
286 |
287 | To connect Spring Boot to a database using JPA:
288 |
289 | 1. Add JPA and database dependencies to `pom.xml`:
290 |
291 | ```xml
292 |
293 | org.springframework.boot
294 | spring-boot-starter-data-jpa
295 |
296 |
297 | com.h2database
298 | h2
299 | runtime
300 |
301 | ```
302 |
303 | 2. Configure database settings in `application.properties`:
304 |
305 | ```properties
306 | spring.datasource.url=jdbc:h2:mem:testdb
307 | spring.datasource.driver-class-name=org.h2.Driver
308 | spring.datasource.username=sa
309 | spring.datasource.password=password
310 | spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
311 | ```
312 |
313 | 3. Create JPA entity and repository:
314 |
315 | ```java
316 | @Entity
317 | public class User {
318 | @Id
319 | @GeneratedValue(strategy = GenerationType.AUTO)
320 | private Long id;
321 | private String name;
322 | // Getters and setters
323 | }
324 |
325 | public interface UserRepository extends JpaRepository {}
326 | ```
327 |
328 | **[⬆ Back to Top](#table-of-contents)**
329 |
330 | 18. ### How to connect Spring Boot application to a database using JDBC?
331 |
332 | To connect Spring Boot to a database using JDBC:
333 |
334 | 1. Add JDBC dependency to `pom.xml`:
335 |
336 | ```xml
337 |
338 | org.springframework.boot
339 | spring-boot-starter-jdbc
340 |
341 | ```
342 |
343 | 2. Configure database settings in `application.properties`:
344 |
345 | ```properties
346 | spring.datasource.url=jdbc:mysql://localhost:3306/mydb
347 | spring.datasource.username=root
348 | spring.datasource.password=root
349 | ```
350 |
351 | 3. Create a `JdbcTemplate` bean:
352 |
353 | ```java
354 | import org.springframework.context.annotation.Bean;
355 | import org.springframework.context.annotation.Configuration;
356 | import org.springframework.jdbc.core.JdbcTemplate;
357 | import javax.sql.DataSource;
358 |
359 | @Configuration
360 | public class DataSourceConfig {
361 | @Bean
362 | public JdbcTemplate jdbcTemplate(DataSource dataSource) {
363 | return new JdbcTemplate(dataSource);
364 | }
365 | }
366 | ```
367 |
368 | **[⬆ Back to Top](#table-of-contents)**
369 |
370 | 19. ### What is @RestController annotation in Spring Boot?
371 |
372 | The `@RestController` annotation is a combination of `@Controller` and `@ResponseBody`. It is used to create RESTful web services by marking a class as a web controller where every method returns a domain object instead of a view.
373 |
374 | Example:
375 |
376 | ```java
377 | import org.springframework.web.bind.annotation.GetMapping;
378 | import org.springframework.web.bind.annotation.RequestMapping;
379 | import org.springframework.web.bind.annotation.RestController;
380 |
381 | @RestController
382 | @RequestMapping("/api")
383 | public class HelloController {
384 | @GetMapping("/hello")
385 | public String sayHello() {
386 | return "Hello, Spring Boot!";
387 | }
388 | }
389 | ```
390 |
391 | **[⬆ Back to Top](#table-of-contents)**
392 |
393 | 20. ### What is @RequestMapping annotation in Spring Boot?
394 |
395 | The `@RequestMapping` annotation is used to map web requests to specific handler methods. It can be used at the class or method level to define the URL patterns for which the methods should be invoked.
396 |
397 | Example:
398 |
399 | ```java
400 | import org.springframework.web.bind.annotation.GetMapping;
401 | import org.springframework.web.bind.annotation.RequestMapping;
402 | import org.springframework.web.bind.annotation.RestController;
403 |
404 | @RestController
405 | @RequestMapping("/api")
406 | public class HelloController {
407 | @GetMapping("/hello")
408 | public String sayHello() {
409 | return "Hello, Spring Boot!";
410 | }
411 | }
412 | ```
413 |
414 | **[⬆ Back to Top](#table-of-contents)**
415 |
416 | 21. ### How does Spring Boot simplify dependency management?
417 |
418 | Spring Boot simplifies dependency management by:
419 |
420 | - **Providing Starters**: Pre-configured dependency sets for common use cases.
421 | - **Auto-Configuration**: Automatically configures application components based on the included dependencies.
422 | - **Dependency Management**: Uses dependency management to handle version conflicts and ensure compatibility.
423 |
424 | **[⬆ Back to Top](#table-of-contents)**
425 |
426 | 22. ### What is the role of embedded servers in Spring Boot?
427 |
428 | Embedded servers in Spring Boot allow applications to be run as standalone Java applications. Spring Boot includes embedded servers like Tomcat, Jetty, and Undertow, which simplifies deployment and reduces the need for external web server setup.
429 |
430 | **[⬆ Back to Top](#table-of-contents)**
431 |
432 | 23. ### What are Profiles in Spring Boot?
433 |
434 | Profiles in Spring Boot are used to segregate parts of your application configuration and make it only available in certain environments. They help in managing different configurations for development, testing, and production.
435 |
436 | Example of using profiles:
437 |
438 | ```properties
439 | # application-dev.properties
440 | server.port=8081
441 |
442 | # application-prod.properties
443 | server.port=80
444 | ```
445 |
446 | **[⬆ Back to Top](#table-of-contents)**
447 |
448 | ## Intermediate Questions
449 |
450 | 1. ### What are the basic Spring Boot annotations?
451 |
452 | Basic Spring Boot annotations include:
453 |
454 | - `@SpringBootApplication`
455 | - `@RestController`
456 | - `@Service`
457 | - `@Repository`
458 | - `@Configuration`
459 | - `@Component`
460 |
461 | **[⬆ Back to Top](#table-of-contents)**
462 |
463 | 2. ### Is it possible to change the port of the embedded Tomcat server in Spring Boot?
464 |
465 | Yes, you can change the port of the embedded Tomcat server by setting the `server.port` property in `application.properties`:
466 |
467 | ```properties
468 | server.port=8081
469 | ```
470 |
471 | **[⬆ Back to Top](#table-of-contents)**
472 |
473 | 3. ### What is the starter dependency of the Spring Boot module?
474 |
475 | A Spring Boot starter is a dependency descriptor that simplifies adding common dependencies. For example, `spring-boot-starter-web` is used for building web applications:
476 |
477 | ```xml
478 |
479 | org.springframework.boot
480 | spring-boot-starter-web
481 |
482 | ```
483 |
484 | **[⬆ Back to Top](#table-of-contents)**
485 |
486 | 4. ### What is the default port of Tomcat in Spring Boot?
487 |
488 | The default port of Tomcat in Spring Boot is `8080`. You can change it by setting the `server.port` property in `application.properties`:
489 |
490 | ```properties
491 | server.port=8081
492 | ```
493 |
494 | **[⬆ Back to Top](#table-of-contents)**
495 |
496 | 5. ### Can we disable the default web server in the Spring Boot application?
497 |
498 | Yes, you can disable the default web server in a Spring Boot application by using the `spring.main.web-application-type` property. Set it to `none`:
499 |
500 | ```properties
501 | spring.main.web-application-type=none
502 | ```
503 |
504 | **[⬆ Back to Top](#table-of-contents)**
505 |
506 | 6. ### How to disable a specific auto-configuration class?
507 |
508 | You can exclude a specific auto-configuration class by using the `@SpringBootApplication` annotation with the `exclude` attribute:
509 |
510 | ```java
511 | @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
512 | public class MyApplication {
513 | public static void main(String[] args) {
514 | SpringApplication.run(MyApplication.class, args);
515 | }
516 | }
517 | ```
518 |
519 | **[⬆ Back to Top](#table-of-contents)**
520 |
521 | 7. ### Can we create a non-web application in Spring Boot?
522 |
523 | Yes, you can create a non-web application in Spring Boot by setting the `spring.main.web-application-type` property to `none` in `application.properties`:
524 |
525 | ```properties
526 | spring.main.web-application-type=none
527 | ```
528 |
529 | **[⬆ Back to Top](#table-of-contents)**
530 |
531 | 8. ### Explain @RestController annotation in Spring Boot.
532 |
533 | The `@RestController` annotation combines `@Controller` and `@ResponseBody`. It is used to create RESTful web services where each method returns a domain object instead of a view. The response is serialized directly to JSON or XML.
534 |
535 | Example:
536 |
537 | ```java
538 | @RestController
539 | @RequestMapping("/api")
540 | public class HelloController {
541 | @GetMapping("/hello")
542 | public String sayHello() {
543 | return "Hello, Spring Boot!";
544 | }
545 | }
546 | ```
547 |
548 | **[⬆ Back to Top](#table-of-contents)**
549 |
550 | 9. ### Difference between @Controller and @RestController?
551 |
552 | - `@Controller`: Used for creating web controllers that return views (HTML, JSP). Methods typically return the name of a view to be rendered.
553 | - `@RestController`: Used for creating RESTful web services. Methods return domain objects, and the response is serialized to JSON or XML.
554 |
555 | **[⬆ Back to Top](#table-of-contents)**
556 |
557 | 10. ### What is the difference between RequestMapping and GetMapping?
558 |
559 | - `@RequestMapping`: Can be used to map HTTP requests to specific handler methods, supporting all HTTP methods (GET, POST, PUT, DELETE, etc.).
560 | - `@GetMapping`: A specialized version of `@RequestMapping` for handling GET requests.
561 |
562 | Example:
563 |
564 | ```java
565 | @RequestMapping("/api")
566 | public class MyController {
567 | @GetMapping("/hello")
568 | public String hello() {
569 | return "Hello!";
570 | }
571 |
572 | @PostMapping("/hello")
573 | public String createHello() {
574 | return "Created!";
575 | }
576 | }
577 | ```
578 |
579 | **[⬆ Back to Top](#table-of-contents)**
580 |
581 | 11. ### What are Profiles in Spring Boot?
582 |
583 | Profiles in Spring Boot allow you to segregate application configuration and make it available only in specific environments. You can define different properties for different profiles (e.g., `dev`, `test`, `prod`).
584 |
585 | Example:
586 |
587 | ```properties
588 | # application-dev.properties
589 | server.port=8081
590 |
591 | # application-prod.properties
592 | server.port=80
593 | ```
594 |
595 | To activate a profile, use:
596 |
597 | ```properties
598 | spring.profiles.active=dev
599 | ```
600 |
601 | **[⬆ Back to Top](#table-of-contents)**
602 |
603 | 12. ### How do you enable Actuator in the Spring Boot application?
604 |
605 | To enable Actuator, add the `spring-boot-starter-actuator` dependency to your `pom.xml`:
606 |
607 | ```xml
608 |
609 | org.springframework.boot
610 | spring-boot-starter-actuator
611 |
612 | ```
613 |
614 | You can then access actuator endpoints such as `/actuator/health` and `/actuator/info`.
615 |
616 | **[⬆ Back to Top](#table-of-contents)**
617 |
618 | 13. ### How do you handle exceptions in a Spring Boot application?
619 |
620 | You can handle exceptions using `@ControllerAdvice` and `@ExceptionHandler` annotations:
621 |
622 | ```java
623 | @ControllerAdvice
624 | public class GlobalExceptionHandler {
625 | @ExceptionHandler(Exception.class)
626 | public ResponseEntity handleException(Exception ex) {
627 | return new ResponseEntity<>("An error occurred: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
628 | }
629 | }
630 | ```
631 |
632 | **[⬆ Back to Top](#table-of-contents)**
633 |
634 | 14. ### What is Swagger in Spring Boot?
635 |
636 | Swagger is a tool used to document and test RESTful APIs. In Spring Boot, you can integrate Swagger using the `springfox-swagger2` and `springfox-swagger-ui` dependencies.
637 |
638 | Example configuration:
639 |
640 | ```xml
641 |
642 | io.springfox
643 | springfox-swagger2
644 | 2.9.2
645 |
646 |
647 | io.springfox
648 | springfox-swagger-ui
649 | 2.9.2
650 |
651 | ```
652 |
653 | **[⬆ Back to Top](#table-of-contents)**
654 |
655 | 15. ### How do you implement security in a Spring Boot application?
656 |
657 | To implement security, add the `spring-boot-starter-security` dependency. Then, configure security settings using `@Configuration` and `@EnableWebSecurity`:
658 |
659 | ```java
660 | @Configuration
661 | @EnableWebSecurity
662 | public class SecurityConfig extends WebSecurityConfigurerAdapter {
663 | @Override
664 | protected void configure(HttpSecurity http) throws Exception {
665 | http
666 | .authorizeRequests()
667 | .anyRequest().authenticated()
668 | .and()
669 | .formLogin();
670 | }
671 | }
672 | ```
673 |
674 | **[⬆ Back to Top](#table-of-contents)**
675 |
676 | 16. ### What are the different ways to configure Spring Boot applications?
677 |
678 | Spring Boot applications can be configured using:
679 |
680 | - `application.properties` or `application.yml` files
681 | - Command-line arguments
682 | - Environment variables
683 | - Java configuration classes with `@Configuration` and `@Bean`
684 |
685 | **[⬆ Back to Top](#table-of-contents)**
686 |
687 | 17. ### What is Spring Data JPA, and how does it differ from Hibernate?
688 |
689 | Spring Data JPA is a part of the Spring Data project that simplifies database access and integrates JPA with Spring. Hibernate is a JPA implementation. Spring Data JPA provides additional functionality like repositories and query methods to ease data access.
690 |
691 | **[⬆ Back to Top](#table-of-contents)**
692 |
693 | 18. ### How do you use Spring Boot with Docker?
694 |
695 | To use Spring Boot with Docker, create a `Dockerfile`:
696 |
697 | ```dockerfile
698 | FROM openjdk:17-jdk
699 | COPY target/myapp.jar /myapp.jar
700 | ENTRYPOINT ["java", "-jar", "/myapp.jar"]
701 | ```
702 |
703 | Build and run the Docker image:
704 |
705 | ```bash
706 | docker build -t myapp .
707 | docker run -p 8080:8080 myapp
708 | ```
709 |
710 | **[⬆ Back to Top](#table-of-contents)**
711 |
712 | 19. ### What is the difference between @Component, @Service, and @Repository annotations?
713 |
714 | - `@Component`: Generic stereotype for any Spring-managed component.
715 | - `@Service`: Specialized form of `@Component`, typically used for service-layer beans.
716 | - `@Repository`: Specialized form of `@Component`, used for data access layer beans with additional exception translation capabilities.
717 |
718 | **[⬆ Back to Top](#table-of-contents)**
719 |
720 | 20. ### How do you test RESTful services in Spring Boot?
721 |
722 | You can test RESTful services using `@WebMvcTest` or `@SpringBootTest` with tools like `MockMvc`:
723 |
724 | ```java
725 | @WebMvcTest(HelloController.class)
726 | public class HelloControllerTest {
727 | @Autowired
728 | private MockMvc mockMvc;
729 |
730 | @Test
731 | public void testHello() throws Exception {
732 | mockMvc.perform(get("/api/hello"))
733 | .andExpect(status().isOk())
734 | .andExpect(content().string("Hello, Spring Boot!"));
735 | }
736 | }
737 | ```
738 |
739 | **[⬆ Back to Top](#table-of-contents)**
740 |
741 | 21. ### How do you configure multiple data sources in Spring Boot?
742 |
743 | To configure multiple data sources, define multiple `DataSource` beans and use `@Primary` to indicate the default one:
744 |
745 | ```java
746 | @Configuration
747 | public class DataSourceConfig {
748 | @Bean
749 | @Primary
750 | @ConfigurationProperties("spring.datasource.primary")
751 | public DataSource primaryDataSource() {
752 | return DataSourceBuilder.create().build();
753 | }
754 |
755 | @Bean
756 | @ConfigurationProperties("spring.datasource.secondary")
757 | public DataSource secondaryDataSource() {
758 | return DataSourceBuilder.create().build();
759 | }
760 | }
761 | ```
762 |
763 | **[⬆ Back to Top](#table-of-contents)**
764 |
765 | 22. ### What is the purpose of the @Autowired annotation?
766 |
767 | The `@Autowired` annotation is used for dependency injection. It allows Spring to automatically inject the required dependencies into a bean.
768 |
769 | **[⬆ Back to Top](#table-of-contents)**
770 |
771 | 23. ### How do you handle CORS in Spring Boot?
772 |
773 | You can handle CORS by configuring it globally or at the controller level. For global configuration:
774 |
775 | ```java
776 | @Configuration
777 | public class WebConfig implements WebMvcConfigurer {
778 | @Override
779 | public void addCorsMappings(CorsRegistry registry) {
780 | registry.addMapping("/**")
781 | .allowedOrigins("http://localhost:3000")
782 | .allowedMethods("GET", "POST", "PUT", "DELETE");
783 | }
784 | }
785 | ```
786 |
787 | **[⬆ Back to Top](#table-of-contents)**
788 |
789 | ## Advanced Question
790 |
791 | 1. ### What are the annotations used to create an Interceptor in Spring Boot?
792 |
793 | To create an Interceptor, use the `@Component` annotation to define it as a Spring bean and implement the `HandlerInterceptor` interface:
794 |
795 | ```java
796 | @Component
797 | public class MyInterceptor implements HandlerInterceptor {
798 | @Override
799 | public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
800 | // Logic before the request is handled
801 | return true;
802 | }
803 |
804 | @Override
805 | public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
806 | // Logic after the request is handled
807 | }
808 |
809 | @Override
810 | public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
811 | // Logic after the request completes
812 | }
813 | }
814 | ```
815 |
816 | Register the interceptor with Spring:
817 |
818 | ```java
819 | @Configuration
820 | public class WebConfig implements WebMvcConfigurer {
821 | @Autowired
822 | private MyInterceptor myInterceptor;
823 |
824 | @Override
825 | public void addInterceptors(InterceptorRegistry registry) {
826 | registry.addInterceptor(myInterceptor);
827 | }
828 | }
829 | ```
830 |
831 | **[⬆ Back to Top](#table-of-contents)**
832 |
833 | 2. ### What is the purpose of Swagger in Spring Boot?
834 |
835 | Swagger is used to document and test RESTful APIs. It generates interactive API documentation and provides a user interface for testing endpoints.
836 |
837 | To integrate Swagger, add the following dependencies:
838 |
839 | ```xml
840 |
841 | io.springfox
842 | springfox-swagger2
843 | 2.9.2
844 |
845 |
846 | io.springfox
847 | springfox-swagger-ui
848 | 2.9.2
849 |
850 | ```
851 |
852 | Configure Swagger:
853 |
854 | ```java
855 | @Configuration
856 | @EnableSwagger2
857 | public class SwaggerConfig {
858 | @Bean
859 | public Docket api() {
860 | return new Docket(DocumentationType.SWAGGER_2)
861 | .select()
862 | .apis(RequestHandlerSelectors.any())
863 | .paths(PathSelectors.any())
864 | .build();
865 | }
866 | }
867 | ```
868 |
869 | Access the Swagger UI at `/swagger-ui.html`.
870 |
871 | **[⬆ Back to Top](#table-of-contents)**
872 |
873 | 3. ### What are the differences between Spring Data JPA and Hibernate?
874 |
875 | - **Spring Data JPA**: A part of Spring that simplifies data access and integrates JPA with Spring. It provides a repository abstraction and various query methods.
876 | - **Hibernate**: A JPA implementation that provides ORM capabilities for mapping Java objects to database tables. Spring Data JPA can use Hibernate as the JPA provider.
877 |
878 | **[⬆ Back to Top](#table-of-contents)**
879 |
880 | 4. ### How do you use Spring Boot with Docker?
881 |
882 | To use Spring Boot with Docker, create a `Dockerfile` in the root of your project:
883 |
884 | ```dockerfile
885 | FROM openjdk:17-jdk
886 | COPY target/myapp.jar /myapp.jar
887 | ENTRYPOINT ["java", "-jar", "/myapp.jar"]
888 | ```
889 |
890 | Build and run the Docker image:
891 |
892 | ```bash
893 | docker build -t myapp .
894 | docker run -p 8080:8080 myapp
895 | ```
896 |
897 | **[⬆ Back to Top](#table-of-contents)**
898 |
899 | 5. ### How to implement caching in Spring Boot?
900 |
901 | To implement caching, add the `spring-boot-starter-cache` dependency and enable caching with `@EnableCaching`:
902 |
903 | ```xml
904 |
905 | org.springframework.boot
906 | spring-boot-starter-cache
907 |
908 | ```
909 |
910 | ```java
911 | @Configuration
912 | @EnableCaching
913 | public class CacheConfig {
914 | }
915 | ```
916 |
917 | Use the `@Cacheable` annotation to cache method results:
918 |
919 | ```java
920 | @Service
921 | public class MyService {
922 | @Cacheable("myCache")
923 | public String getCachedValue(String key) {
924 | // Method logic
925 | }
926 | }
927 | ```
928 |
929 | **[⬆ Back to Top](#table-of-contents)**
930 |
931 | 6. ### How to configure Spring Boot for asynchronous processing?
932 |
933 | Enable asynchronous processing with `@EnableAsync` and use `@Async` for asynchronous methods:
934 |
935 | ```java
936 | @Configuration
937 | @EnableAsync
938 | public class AsyncConfig {
939 | }
940 | ```
941 |
942 | ```java
943 | @Service
944 | public class MyService {
945 | @Async
946 | public CompletableFuture asyncMethod() {
947 | // Asynchronous logic
948 | return CompletableFuture.completedFuture("result");
949 | }
950 | }
951 | ```
952 |
953 | **[⬆ Back to Top](#table-of-contents)**
954 |
955 | 7. ### How do you configure multiple data sources in Spring Boot?
956 |
957 | Define multiple `DataSource` beans in a configuration class:
958 |
959 | ```java
960 | @Configuration
961 | public class DataSourceConfig {
962 | @Bean
963 | @Primary
964 | @ConfigurationProperties("spring.datasource.primary")
965 | public DataSource primaryDataSource() {
966 | return DataSourceBuilder.create().build();
967 | }
968 |
969 | @Bean
970 | @ConfigurationProperties("spring.datasource.secondary")
971 | public DataSource secondaryDataSource() {
972 | return DataSourceBuilder.create().build();
973 | }
974 | }
975 | ```
976 |
977 | **[⬆ Back to Top](#table-of-contents)**
978 |
979 | 8. ### What is the purpose of @ComponentScan in the class files?
980 |
981 | The `@ComponentScan` annotation is used to specify the packages to scan for Spring components, such as `@Component`, `@Service`, `@Repository`, and `@Controller`.
982 |
983 | ```java
984 | @Configuration
985 | @ComponentScan(basePackages = "com.example.myapp")
986 | public class AppConfig {
987 | }
988 | ```
989 |
990 | **[⬆ Back to Top](#table-of-contents)**
991 |
992 | 9. ### How to monitor a Spring Boot application using Actuator?
993 |
994 | Spring Boot Actuator provides monitoring endpoints. Enable it by adding the `spring-boot-starter-actuator` dependency:
995 |
996 | ```xml
997 |
998 | org.springframework.boot
999 | spring-boot-starter-actuator
1000 |
1001 | ```
1002 |
1003 | Access endpoints like `/actuator/health` and `/actuator/metrics` to monitor the application.
1004 |
1005 | **[⬆ Back to Top](#table-of-contents)**
1006 |
1007 | 10. ### How do you implement distributed tracing in a Spring Boot application using OpenTelemetry?
1008 |
1009 | Add dependencies for OpenTelemetry and configure it:
1010 |
1011 | ```xml
1012 |
1013 | io.opentelemetry
1014 | opentelemetry-sdk-extension-autoconfigure-spring-boot
1015 | 1.7.2
1016 |
1017 | ```
1018 |
1019 | Configure OpenTelemetry in `application.properties`:
1020 |
1021 | ```properties
1022 | otel.exporter.otlp.endpoint=http://localhost:4317
1023 | ```
1024 |
1025 | Use the OpenTelemetry API to instrument your code.
1026 |
1027 | **[⬆ Back to Top](#table-of-contents)**
1028 |
1029 | 11. ### How do you enable HTTPS in a Spring Boot application?
1030 |
1031 | To enable HTTPS, configure SSL in `application.properties`:
1032 |
1033 | ```properties
1034 | server.port=8443
1035 | server.ssl.key-store=classpath:keystore.p12
1036 | server.ssl.key-store-password=password
1037 | server.ssl.key-store-type=PKCS12
1038 | ```
1039 |
1040 | Place the `keystore.p12` file in `src/main/resources`.
1041 |
1042 | **[⬆ Back to Top](#table-of-contents)**
1043 |
1044 | 12. ### What is Spring Boot WebFlux?
1045 |
1046 | Spring Boot WebFlux is a reactive web framework that supports non-blocking and asynchronous processing. It is an alternative to the traditional Spring MVC framework for building reactive applications.
1047 |
1048 | **[⬆ Back to Top](#table-of-contents)**
1049 |
1050 | 13. ### What is reactive programming in Spring Boot?
1051 |
1052 | Reactive programming is a paradigm that deals with asynchronous data streams and the propagation of changes. Spring Boot supports reactive programming with the Reactor framework.
1053 |
1054 | **[⬆ Back to Top](#table-of-contents)**
1055 |
1056 | 14. ### How do you deploy a Spring Boot application as a WAR file?
1057 |
1058 | To deploy as a WAR file, modify `pom.xml` to package the application as a WAR:
1059 |
1060 | ```xml
1061 | war
1062 | ```
1063 |
1064 | Extend `SpringBootServletInitializer` in your main application class:
1065 |
1066 | ```java
1067 | @SpringBootApplication
1068 | public class MyApplication extends SpringBootServletInitializer {
1069 | @Override
1070 | protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
1071 | return application.sources(MyApplication.class);
1072 | }
1073 |
1074 | public static void main(String[] args) {
1075 | SpringApplication.run(MyApplication.class, args);
1076 | }
1077 | }
1078 | ```
1079 |
1080 | Build the WAR file with:
1081 |
1082 | ```bash
1083 | mvn clean package
1084 | ```
1085 |
1086 | **[⬆ Back to Top](#table-of-contents)**
1087 |
1088 | 15. ### How do you integrate Spring Boot with RabbitMQ?
1089 |
1090 | Add the `spring-boot-starter-amqp` dependency:
1091 |
1092 | ```xml
1093 |
1094 | org.springframework.boot
1095 | spring-boot-starter-amqp
1096 |
1097 | ```
1098 |
1099 | Configure RabbitMQ settings in `application.properties`:
1100 |
1101 | ```properties
1102 | spring.rabbitmq.host=localhost
1103 | spring.rabbitmq.port=5672
1104 | ```
1105 |
1106 | Define a message listener:
1107 |
1108 | ```java
1109 | @Component
1110 | public class MyMessageListener {
1111 | @RabbitListener(queues = "myQueue")
1112 | public void receiveMessage(String message) {
1113 | System.out.println("Received: " + message);
1114 | }
1115 | }
1116 | ```
1117 |
1118 | **[⬆ Back to Top](#table-of-contents)**
1119 |
1120 | 16. ### How do you configure a data source in Spring Boot?
1121 |
1122 | Configure the data source in `application.properties`:
1123 |
1124 | ```properties
1125 | spring.datasource.url=jdbc:mysql://localhost:3306/mydb
1126 | spring.datasource.username=root
1127 | spring.datasource.password=password
1128 | ```
1129 |
1130 | **[⬆ Back to Top](#table-of-contents)**
1131 |
1132 | 17. ### How do you use Spring Boot with Kubernetes?
1133 |
1134 | Create a Docker image of your Spring Boot application and deploy it on Kubernetes using a YAML configuration file. Define a deployment and service in `deployment.yaml`:
1135 |
1136 | ```yaml
1137 | apiVersion: apps/v1
1138 | kind: Deployment
1139 | metadata:
1140 | name: myapp
1141 | spec:
1142 | replicas: 1
1143 | selector:
1144 | matchLabels:
1145 | app: myapp
1146 | template:
1147 | metadata:
1148 | labels:
1149 | app: myapp
1150 | spec:
1151 | containers:
1152 | - name: myapp
1153 | image: myapp:latest
1154 | ports:
1155 | - containerPort: 8080
1156 | ---
1157 | apiVersion: v1
1158 | kind: Service
1159 | metadata:
1160 | name: myapp-service
1161 | spec:
1162 | ports:
1163 | - port: 80
1164 | targetPort: 8080
1165 | selector:
1166 | app: myapp
1167 | ```
1168 |
1169 | Apply the configuration with:
1170 |
1171 | ```bash
1172 | kubectl apply -f deployment.yaml
1173 | ```
1174 |
1175 | **[⬆ Back to Top](#table-of-contents)**
1176 |
1177 | 18. ### How do you secure a Spring Boot REST API using OAuth2?
1178 |
1179 | Add the `spring-boot-starter-oauth2-client` dependency:
1180 |
1181 | ```xml
1182 |
1183 | org.springframework.boot
1184 | spring-boot-starter-oauth2-client
1185 |
1186 | ```
1187 |
1188 | Configure OAuth2 client settings in `application.properties`:
1189 |
1190 | ```properties
1191 | spring.security.oauth2.client.registration.google.client-id=your-client-id
1192 | spring.security.oauth2.client.registration.google.client-secret=your-client-secret
1193 | ```
1194 |
1195 | **[⬆ Back to Top](#table-of-contents)**
1196 |
1197 | ## Disclaimer
1198 |
1199 | The questions provided in this repository are the summary of frequently asked questions across numerous companies. We cannot guarantee that these questions will actually be asked during your interview process, nor should you focus on memorizing all of them. The primary purpose is for you to get a sense of what some companies might ask — do not get discouraged if you don't know the answer to all of them — that is ok!
1200 |
1201 | Good luck with your interview 😊
1202 |
--------------------------------------------------------------------------------