└── README.md /README.md: -------------------------------------------------------------------------------- 1 | # 100 Fundamental Spring Interview Questions in 2025 2 | 3 |
4 |

5 | 6 | web-and-mobile-development 7 | 8 |

9 | 10 | #### You can also find all 100 answers here πŸ‘‰ [Devinterview.io - Spring](https://devinterview.io/questions/web-and-mobile-development/spring-interview-questions) 11 | 12 |
13 | 14 | ## 1. What is the _Spring Framework_ and what are its core features? 15 | 16 | The **Spring Framework** is a comprehensive software platform that provides infrastructure support for developing enterprise-level applications. It's known for its robust features that simplify complex tasks and for its support of best coding practices. 17 | 18 | ### Core Features 19 | 20 | 1. **Inversion of Control (IoC)**: Centralized bean management ensures loose coupling leading to easy maintenance and testing. 21 | 22 | 2. **Aspect-Oriented Programming (AOP)**: Modularizes cross-cutting concerns such as logging and caching, promoting reusability. 23 | 24 | 3. **Validation and Data Binding**: Offers powerful validation and data binding mechanisms compatible with JavaBeans components, thereby ensuring data integrity. 25 | 26 | 4. **JDBC Abstraction and Transactions**: Provides a consistent data access layer and unified transaction management across various data sources. 27 | 28 | 5. **ORM Support**: Simplifies Object-Relational Mapping with tools like Spring Data JPA and Hibernate. 29 | 30 | 6. **MVC Web Framework**: Facilitates the development of flexible web applications and RESTful services. 31 | 32 | 7. **REST Support and Content Negotiation**: Streamlines building RESTful web services and content negotiation for better client/server communication. 33 | 34 | 8. **Security Features**: Offers a robust security framework for web applications, covering authentication, authorization, and access-control decisions. 35 | 36 | 9. **Internationalization and Localization**: Facilitates creating multi-lingual applications by providing extensive support for different languages and regions. 37 | 38 | 10. **Dynamic, Strong-Typed Property Configuration**: The Spring EL (Expression Language) simplifies dynamic resolution of property values in annotations or XML configuration files. 39 | 40 | 11. **Runtime Polymorphism and Dependency Lookup**: Spring provides lightweight, built-in dependency lookup strategies aiding late binding of dependencies. 41 | 42 | 12. **Support for Different Development Styles**: Offers support for various enterprise application patterns like Singleton, Factory, Adapter, and so on. 43 | 44 | 13. **In-Depth Testing Support**: Spring's testing modules provide classes and configurations for thorough unit and integration testing. 45 | 46 | 14. **Java Configuration and Annotation**: 47 | - Spring allows using plain Java classes to define beans and their dependencies, reducing XML configuration overhead. 48 | - Annotations like `@Autowired` enable autowiring of dependencies, promoting developer productivity. 49 | 50 | 15. **Extensive Documentation and Community Support**: Spring has rich, comprehensive documentation and a highly active user community, ensuring reliable support and guidance. 51 | 52 | 16. **Modularity**: Spring, being a modular framework, allows using only the needed modules, minimizing runtime overhead. 53 |
54 | 55 | ## 2. How do you create a simple _Spring_ application? 56 | 57 | To create a **simple Spring application**, you need to handle the following tasks: 58 | 59 | 1. Choose the right Structure for Project 60 | 2. Set the Maven or Gradle configurations 61 | 3. Add the Essential Dependencies 62 | 4. Implement the Main Application 63 | 5. Write a simple Controller or Service for the Application 64 | 65 | ### Project Setup 66 | 67 | Choose your favorite ```Build Management System``` such as Maven or Gradle. 68 | 69 | **Maven Example** - pom.xml: 70 | 71 | ```xml 72 | 73 | 74 | 75 | org.springframework 76 | spring-context 77 | 5.3.10 78 | 79 | 80 | 81 | org.springframework 82 | spring-web 83 | 5.3.10 84 | 85 | 86 | 87 | org.springframework 88 | spring-webmvc 89 | 5.3.10 90 | 91 | 92 | 93 | javax.servlet 94 | javax.servlet-api 95 | 4.0.1 96 | provided 97 | 98 | 99 | ``` 100 | 101 | **Gradle Example** - build.gradle: 102 | 103 | ```gradle 104 | dependencies { 105 | // Core Spring Context 106 | implementation 'org.springframework:spring-context:5.3.10' 107 | // Web Support 108 | implementation 'org.springframework:spring-web:5.3.10' 109 | // Bootstrap Spring Web Application 110 | implementation 'org.springframework:spring-webmvc:5.3.10' 111 | // Javax Servlet API 112 | providedCompile 'javax.servlet:javax.servlet-api:4.0.1' 113 | } 114 | ``` 115 | 116 | ### Key Components for a Web Application 117 | 118 | 1. **DispatcherServlet**: Captures HTTP requests and directs them to the right controllers. 119 | 2. **ApplicationContext**: The core container for Spring's IoC and dependency injection features. 120 | 121 | ### Spring Application Main Class 122 | 123 | Here is the Java code: 124 | 125 | ```java 126 | import org.springframework.boot.SpringApplication; 127 | import org.springframework.boot.autoconfigure.SpringBootApplication; 128 | 129 | @SpringBootApplication 130 | public class MySpringApp { 131 | public static void main(String[] args) { 132 | SpringApplication.run(MySpringApp.class, args); 133 | } 134 | } 135 | ``` 136 | 137 | With the `@SpringBootApplication` annotation, Spring Boot takes care of intricate configuration, and you can be started with plain old `public static void main`. 138 | 139 | ### WebController 140 | 141 | Create a simple Controller that listens to GET requests. Here is the Java code: 142 | 143 | **MainController**.java: 144 | 145 | ```java 146 | import org.springframework.stereotype.Controller; 147 | import org.springframework.web.bind.annotation.RequestMapping; 148 | 149 | @Controller 150 | public class MainController { 151 | 152 | @RequestMapping("/") 153 | public String home() { 154 | return "index"; 155 | } 156 | } 157 | ``` 158 |
159 | 160 | ## 3. What is _Inversion of Control (IoC)_? How does _Spring_ facilitate _IoC_? 161 | 162 | **Inversion of Control** is a coding pattern where the control of flow is transferred to a framework or an external system. This mechanism serves as the foundation for **Dependency Injection** and is an integral part of the Spring framework. 163 | 164 | ### How does Spring Support IoC? 165 | 166 | 1. **Bean Management**: Spring manages Java objects, known as beans, by detailing their creation, configuration and deletion through **Bean Factories**. 167 | 168 | 2. **Configurations**: Spring employs both XML and annotations for defining bean configurations. 169 | 170 | 3. **Dependency Resolution and Injection**: Spring ensures that **inter-bean dependencies** are resolved and injected, thereby reducing tight coupling and enhancing testability and flexibility. 171 | 172 | 4. **Lifecycle Management**: Using Spring's **Bean Lifecycle**, you can manage the instantiation, modification and disposal of beans in a systematic manner. 173 | 174 | 5. **AOP and Declarative Services**: Spring aids IoC by offering an Aspect Oriented Programming (AOP) system and allowing declarative services via Java annotations, enabling you to externalize cross-cutting concerns. 175 | 176 | 6. **Externally Managed Resources**: You can bring in non-bean resources like data sources and template files under Spring IoC management, promoting resource sharing and centralization. 177 | 178 | ### Java Example: IoC with Spring 179 | 180 | #### Maven Dependency 181 | 182 | Add the following Spring Core dependency to your Maven `pom.xml`: 183 | 184 | ```xml 185 | 186 | 187 | org.springframework 188 | spring-core 189 | 5.3.10 190 | 191 | 192 | ``` 193 | 194 | #### Bean Configuration (XML) 195 | 196 | Define your beans in an XML file, typically named `applicationContext.xml`: 197 | 198 | ```xml 199 | 203 | 204 | 205 | 206 | 207 | 208 | ``` 209 | 210 | #### Bean Configuration (Annotations) 211 | 212 | In addition to XML-based configuration, you can use annotations. Add this to your XML bean container: 213 | 214 | ```java 215 | @Configuration 216 | public class AppConfig { 217 | @Bean 218 | public Customer customer() { 219 | Customer cust = new Customer(); 220 | cust.setItemName("Laptop"); 221 | return cust; 222 | } 223 | @Bean 224 | public Invoice invoice() { 225 | return new Invoice(); 226 | } 227 | } 228 | ``` 229 | 230 | #### Application Entry Point: Main 231 | 232 | In your main application, retrieve beans from the Spring container: 233 | 234 | ```java 235 | public class Main { 236 | public static void main(String[] args) { 237 | ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); 238 | // XML-based instantiation 239 | Customer c1 = (Customer) context.getBean("customer"); 240 | 241 | AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); 242 | // Annotation-based instantiation 243 | Customer c2 = context.getBean(Customer.class); 244 | 245 | // Perform operations with beans 246 | } 247 | } 248 | ``` 249 | 250 | In this example, both XML-based and annotation-based IoC and bean management are depicted. 251 |
252 | 253 | ## 4. What is the _ApplicationContext_ in _Spring_? 254 | 255 | The `ApplicationContext` is at the core of Spring, serving as a **container** for managing and configuring the application's **beans** (components) and their lifecycle. The `ApplicationContext` is crucial for Inversion of Control (IoC) and Dependency Injection (DI). 256 | 257 | ### How It Works 258 | 259 | - **Configuration Management**: This is a central repository for bean definitions, either specified in XML configuration, Java annotations, or XML configuration. 260 | 261 | - **Bean Instantiation and Injection**: The `ApplicationContext` is responsible for creating and wiring beans based on the provided configuration. 262 | 263 | - **Lifecycles**: The container manages bean lifecycles, initializing and destroying them when the application starts or shuts down. 264 | 265 | ### Bean Scopes 266 | 267 | - **Singleton**: The default. The `ApplicationContext` creates and manages a single instance of a bean. 268 | - **Prototype**: Each request or lookup results in a new bean instance. 269 | 270 | There are also less commonly used scopes, such as `request`, `session`, `global session`, and `application`. 271 | 272 | ### Common `ApplicationContext` Implementations 273 | 274 | - **ClassPathXmlApplicationContext**: Loads the context configuration from an XML file located in the classpath. 275 | - **FileSystemXmlApplicationContext**: Similar to `ClassPathXmlApplicationContext`, this loads from an XML file but requires a file system path. 276 | - **AnnotationConfigApplicationContext**: Reads the configuration classes produced with Java annotations. 277 | - **GenericWebApplicationContext**: Designed for web-aware applications and compatible with Servlet 3.0 environments. 278 | 279 | ### Close vs. Refresh 280 | 281 | - **Close**: Shuts down the container, releasing resources and triggering bean destruction if necessary. 282 | - **Refresh**: Usually used with web applications to perform a manual refresh of the `ApplicationContext` after it's been initialized. 283 | 284 | ### Code Example: Initializing the `ApplicationContext` 285 | 286 | Below is the Java code: 287 | 288 | ```java 289 | import org.springframework.context.ApplicationContext; 290 | import org.springframework.context.support.ClassPathXmlApplicationContext; 291 | 292 | public class MyApp { 293 | public static void main(String[] args) { 294 | ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); 295 | MyBean myBean = context.getBean(MyBean.class); 296 | myBean.doSomething(); 297 | ((ClassPathXmlApplicationContext) context).close(); // Shuts down the context 298 | } 299 | } 300 | ``` 301 | In modern Spring applications, Java configuration and annotations, such as `@Configuration` and `@Bean` methods, are typically used for initializing the `ApplicationContext`. 302 | 303 | Here is the corresponding code: 304 | 305 | ```java 306 | import org.springframework.context.annotation.AnnotationConfigApplicationContext; 307 | import org.springframework.context.support.AbstractApplicationContext; 308 | import org.springframework.context.annotation.Bean; 309 | import org.springframework.context.annotation.Configuration; 310 | 311 | public class MyApp { 312 | public static void main(String[] args) { 313 | ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); 314 | MyBean myBean = context.getBean(MyBean.class); 315 | myBean.doSomething(); 316 | ((AbstractApplicationContext) context).close(); // Shuts down the context 317 | } 318 | 319 | @Configuration 320 | public static class AppConfig { 321 | @Bean 322 | public MyBean myBean() { 323 | return new MyBean(); 324 | } 325 | } 326 | } 327 | ``` 328 | 329 | In this example, both the XML-based and Java-based configurations illustrate the setup of the `ApplicationContext`. 330 | 331 | ### Best Practices 332 | 333 | - **Keep It Lightweight**: Overly complex configurations can lead to decreased application performance. 334 | - **Know Your Bean Lifecycle**: Be mindful of singleton versus prototype scopes and how beans are initialized or destroyed. 335 | - **Tread Carefully with Bean Scopes**: Common mistakes with bean scopes can lead to unanticipated behavior. 336 | - **Use the Best-suited Configuration for Your Application**: Assess the requirements of your project to select the most efficient means of configuring the `ApplicationContext`. 337 |
338 | 339 | ## 5. Explain _Dependency Injection_ and its types in the _Spring_ context. 340 | 341 | **Dependency Injection** (DI) is a fundamental concept in the **Spring Framework** and serves as a key advantage over traditional, direct dependencies management. 342 | 343 | ### Benefits 344 | 345 | - **Easy to Manage and Test**: Dependencies can be swapped for testing and changed at runtime. 346 | - **Decoupling**: Promotes separation of concerns and reduces inter-class coupling. 347 | - **Increased Reusability**: Makes components more reusable across systems. 348 | 349 | ### What DI Solves 350 | 351 | Conventional approach: 352 | 353 | - When a class $A$ needs an instance of class $B$, $A$ is responsible for creating $B$ (e.g., using `new`) and introducing a hard dependency, hindering flexibility and testability. 354 | 355 | ### Core Components 356 | 357 | 1. **Client**: The class requesting the dependency. 358 | 2. **Injector**: Often, it's a framework or container supplying the dependency. 359 | 3. **Service**: The class fulfilling the dependency requirement. 360 | 361 | ### Types of Dependency Injection 362 | 363 | 1. **Constructor Injection**: The \textit{Injector} provides all the necessary dependencies through the constructor. 364 | 365 | **Pros**: 366 | - The object is always in a valid state when returned. 367 | - It's clearer which dependencies are needed. 368 | 369 | **Cons**: 370 | - Constructors can grow in size. 371 | - May not be suitable when there are optional or too many dependencies. 372 | 373 | 2. **Setter Method Injection**: The \textit{Injector} uses setter methods to inject the dependencies after the object is created. 374 | 375 | **Pros**: 376 | - No need to extend classes to pass dependencies. 377 | - Doesn't inject dependencies that are not needed. 378 | 379 | **Cons**: 380 | - The object can be in an inconsistent state until all dependencies are set. 381 | 382 | 3. **Field Injection**: Dependencies are provided directly into the fields or properties of the class. 383 | 384 | **Pros**: 385 | - Often requires less boilerplate. 386 | - Can be the simplest form of DI setup. 387 | 388 | **Cons**: 389 | - The class's dependencies are not immediately visible from its constructor or methods. 390 | - Difficult to ensure that dependencies are not `null`. 391 | - Breaks the encapsulation principle. 392 | 393 | 4. **Method Injection (Less Common)**: Dependencies are injected through methods that are called after object construction. While this fulfills the Dependency Injection criteria, it's less frequently seen in the Spring context. 394 | 395 | **Pros**: 396 | - Allows for flexibility in when a dependency is needed. 397 | 398 | **Cons**: 399 | - Increases complexity as clients need to manage when to call these methods. 400 | - Breaks encapsulation. 401 | 402 | ### Code Example: Dependency Injection Types 403 | 404 | Here is the Java code: 405 | 406 | ```java 407 | /* Constructor Injection */ 408 | public class ReportService { 409 | private final DatabaseRepository databaseRepository; 410 | 411 | public ReportService(DatabaseRepository databaseRepository) { 412 | this.databaseRepository = databaseRepository; 413 | } 414 | } 415 | 416 | /* Setter Method Injection */ 417 | public class ReportService { 418 | private DatabaseRepository databaseRepository; 419 | 420 | public void setDatabaseRepository(DatabaseRepository databaseRepository) { 421 | this.databaseRepository = databaseRepository; 422 | } 423 | } 424 | 425 | /* Field Injection - Directly assigns the dependency. */ 426 | @Component 427 | public class ReportService { 428 | @Autowired 429 | private DatabaseRepository databaseRepository; 430 | } 431 | 432 | /* Method Injection - Injects the dependency via a method call post-construction. */ 433 | public class ReportService { 434 | private DatabaseRepository databaseRepository; 435 | 436 | public void injectDependency(DatabaseRepository databaseRepository) { 437 | this.databaseRepository = databaseRepository; 438 | } 439 | } 440 | ``` 441 |
442 | 443 | ## 6. What are _Bean Scopes_ in _Spring_? Name them. 444 | 445 | **Spring** allows you to specify different **bean scopes**. Each scope serves a unique lifecycle and context interaction. 446 | 447 | ### Types of Bean Scopes 448 | 449 | 1. **Singleton** (default): A single bean instance is managed per container. This scope is suitable for stateless beans. 450 | 451 | 2. **Prototype**: A new instance per bean reference or look-up. This scope is beneficial for stateful beans. 452 | 453 | 3. **Request**: A single bean instance is tied to an **HTTP** request in a **web-aware** container. This scope is ideal for beans that are required within an HTTP request, such as web controllers. 454 | 455 | 4. **Session**: Physically represents a single user session in a **web-aware** container. Objects in this scope exist for as long as the HTTP **session** endures. 456 | 457 | 5. **Global Session**: Functions similarly to the **Session** scope, but is meant for **portlet-based environments**. 458 | 459 | 6. **Application**: Deprecated. Used to create a bean for the **lifetime of a **`ServletContext`** in **web-aware** containers. 460 | 461 | 7. **WebSocket**: Introduced in Spring 5.0, this scope is associated with the lifecycle of a WebSocket connection. The bean will remain in scope as long as the WebSocket connection is active. It's often used for managing attributes and operations related to the WebSocket session. 462 |
463 | 464 | ## 7. How do you configure a _bean_ in _Spring_? 465 | 466 | In Spring, a **bean** represents an object that's managed by the Spring IoC (Inversion of Control) Container. Developers can configure beans using annotations, XML, or Java code. 467 | 468 | ### Key Bean Configuration Elements 469 | 470 | - **Class**: Identifies the bean's type. 471 | - **ID/Name**: Unique identifier for the bean within the IoC container. 472 | - **Scope**: Describes the bean's lifecycle. 473 | - **Dependencies**: Bean dependencies and corresponding wiring mode. 474 | - **Additional Settings**: Custom properties and configurations. 475 | 476 | ### Annotation-Based Bean Configuration 477 | 478 | Use the `@Component` family of annotations combined with `@Autowired`. 479 | 480 | - **@Component**: Indicates the class as a Spring-managed component. 481 | - **@Repository**: Specialized for data access. 482 | - **@Service**: For business services. 483 | - **@Controller**: Designed for MVC web applications. 484 | 485 | **Example: Using @Component** 486 | 487 | Here is the Java code: 488 | 489 | ```java 490 | import org.springframework.stereotype.Component; 491 | 492 | @Component 493 | public class MyService { 494 | // Bean logic here 495 | } 496 | ``` 497 | 498 | ### XML-Based Bean Configuration 499 | 500 | The traditional method uses XML configuration. 501 | 502 | - **bean**: The XML element that defines a Spring bean. 503 | - **id**: Unique identifier. 504 | - **class**: Specifies the bean's class. 505 | 506 | **Example: XML-Configured Bean** 507 | 508 | Here is the XML code: 509 | 510 | ```xml 511 | 515 | 516 | 517 | 518 | ``` 519 | 520 | ### Java Configuration 521 | 522 | Modern Spring applications often favor Java-based configuration using `@Configuration` and `@Bean` annotations. 523 | 524 | - **@Configuration**: Marks a class as providing bean configurations. 525 | - **@Bean**: Identifies a method that returns a bean instance. 526 | 527 | **Example: Java-Based Configuration** 528 | 529 | Here is the Java code: 530 | 531 | ```java 532 | import org.springframework.context.annotation.Bean; 533 | import org.springframework.context.annotation.Configuration; 534 | 535 | @Configuration 536 | public class AppConfig { 537 | @Bean 538 | public MyService myService() { 539 | return new MyService(); 540 | } 541 | } 542 | ``` 543 |
544 | 545 | ## 8. Describe the role of the _Spring Core container_. 546 | 547 | **Spring Core container** serves as the foundation for the Spring Framework, providing the **inversion of control** (IoC) and **dependency injection** (DI) mechanisms. 548 | 549 | ### Key Responsibilities 550 | 551 | - **Lifecycle Management**: Ensures components' lifecycle through configuration and specific hooks (such as `@PostConstruct` and `@PreDestroy` annotations). 552 | - **Configuration Management**: Enables bean definitions through XML, annotations, or Java-based configurations. 553 | - **Context Metadata Management**: Houses metadata, like scoped dependencies and convenient mechanisms, such as expressions and environment configuration. 554 | 555 | ### Primary Components 556 | 557 | - **BeanFactory**: The basic IoC container, which is primarily responsible for the instantiation and management of beans. It provides basic features of DI and doesn't support advanced features such as AOP. 558 | - **ApplicationContext**: This is an advanced version of the BeanFactory. It incorporates all the functionalities of the BeanFactory and adds context-specific behavior. It's the prevalent choice for most scenarios and stands as the client's gateway into the Spring world. It provides additional features such as AOP, message source, and event publication. 559 | 560 | ### Registration and Location of Beans 561 | 562 | - **Explicit Registration**: Developers can define beans either in XML configuration files or using annotations (like `@Component`, `@Service`, `@Repository`, `@Controller`) and Java-based configurations. 563 | - **Implicit Registration**: Some classes in Spring are automatically detected and registered if the necessary annotations are present. 564 | 565 | ### Bean Scopes 566 | 567 | The container manages a bean's lifecycle and its visibility from other beans based on the bean scope. 568 | 569 | #### Primary Scopes 570 | 571 | - **Singleton**: The default scope, where a single instance is managed per container. 572 | - **Prototype**: Defines that a new instance should be created and managed each time it's requested. 573 | 574 | #### Extended Scopes 575 | 576 | - **Request**: In web-aware applications, a bean is created on each HTTP request. 577 | - **Session**: Like 'Request' but scoped to an HTTP session. 578 | - **Global Session**: Similar to 'Session' but applies to portlet-based applications. 579 | 580 | ### Custom Scopes 581 | 582 | Developers can **define their own scopes** to handle specific requirements. 583 | 584 | ### IoC and DI Mechanisms 585 | 586 | - **Inversion of Control (IoC)**: Refers to the pattern in which objects delegate the responsibility of their creation and management to another party (the IoC container). 587 | - **Dependency Injection (DI)**: Describes the process of providing the dependencies (collaborating objects) to a component from an external source. 588 | 589 | ### Practical Benefits 590 | 591 | - **Loose Coupling**: Components are less dependent on each other, which enhances system flexibility and maintainability. 592 | - **Simplified Unit Testing**: Easier with singletons and DI, as you can mock or provide test-specific dependencies. 593 | - **Centralized Configuration**: Configuration details are consolidated, simplifying management and reducing the likelihood of redundancy or inconsistencies. 594 | - **Lifecycle Control**: Accurate and centralized bean lifecycle management. 595 | - **Reduced Boilerplate**: Annotations and configurations streamline bean definitions and wiring. 596 |
597 | 598 | ## 9. What is a _Spring configuration file_? 599 | 600 | **Spring configuration files** provide a way to configure Spring applications. These files, often written in XML, contain **bean definitions** and other configuration elements. 601 | 602 | ### Key Elements 603 | 604 | - **Bean Definitions**: XML files define beans using `bean` elements, or annotation-based configurations can be used. 605 | 606 | - **Module Configurations**: These files specify Spring modules to use, such as `context`, `mvc`, or `aop`. 607 | 608 | - **External Configurations**: XML files can import other Spring configurations, often used in larger projects. 609 | 610 | ```xml 611 | 612 | ``` 613 | 614 | ### Roles and Responsibilities 615 | 616 | - **Central Configuration Repository**: Provides a central place for application-specific and infrastructure-level configurations. 617 | 618 | - **Dependency Injection Configuration**: Specifies dependencies and how they should be injected into beans. 619 | 620 | - **Both In-Built Configuration and Custom Configurations**: Accommodates Spring's in-built configurations and custom configurations for applications and components. 621 | 622 | - **External Configuration Import**: Allows the modular composition of application configurations. 623 | 624 | ### Best Practices 625 | 626 | - **Separation of Concerns**: Divide configuration files based on the functional parts they control, such as one for data access and another for web components. 627 | 628 | - **Consistency and Standardization**: Establish best practices across the team. This ensures that configurations are maintained uniformly. 629 | 630 | - **Minimize Global Settings**: While Spring offers a global application context, it’s often better to have smaller, more focused contexts for specific application layers or modules. 631 | 632 | ### Code Example: Spring Configuration File 633 | 634 | Here is the XML configuration: 635 | 636 | ```xml 637 | 638 | 639 | 640 | 641 | 642 | 643 | 644 | 645 | 646 | 647 | ``` 648 |
649 | 650 | ## 10. How do you create an _ApplicationContext_ in a _Spring_ application? 651 | 652 | The **ApplicationContext** serves as the core of the Spring IoC container and is fundamental to the setup of any Spring-based application. 653 | 654 | ### Ways to Create ApplicationContext 655 | 656 | 1. **`ClassPathXmlApplicationContext`**: Loads the XML file from the classpath. 657 | 658 | ```java 659 | ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); 660 | ``` 661 | 662 | 2. **`FileSystemXmlApplicationContext`**: Loads the XML file from the filesystem. 663 | 664 | ```java 665 | ApplicationContext context = new FileSystemXmlApplicationContext("path/to/applicationContext.xml"); 666 | ``` 667 | 668 | 3. **`XmlWebApplicationContext`**: Designed for web applications and loads XML from a specified web application context. 669 | 670 | ```java 671 | ApplicationContext context = new XmlWebApplicationContext(); 672 | ``` 673 | 674 | 4. **`AnnotationConfigApplicationContext`**: When employing Java configuration with `@Configuration` classes. 675 | 676 | ```java 677 | ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); 678 | ``` 679 | 680 | 5. **`GenericApplicationContext`**: A flexible option for advanced customizations. 681 | 682 | ```java 683 | GenericApplicationContext context = new GenericApplicationContext(); 684 | context.refresh(); // Call refresh manually 685 | ``` 686 | 687 | 6. **`GenericXmlApplicationContext`**: Lets you control how the XML is read. 688 | 689 | ```java 690 | GenericXmlApplicationContext context = new GenericXmlApplicationContext(); 691 | context.load("path/to/applicationContext.xml"); 692 | context.refresh(); 693 | ``` 694 | 695 | 7. **`SilentModeApplicationContext`**: Quiets any startup messages. 696 | 697 | ```java 698 | ApplicationContext context = new SilentModeApplicationContext(); 699 | ``` 700 | 701 | ### Best Practices 702 | 703 | - **Type Safety**: Opt for `AnnotationConfigApplicationContext` or Java-based `ApplicationConfig` whenever possible. 704 | 705 | - **XML vs. Java-based Config**: XML is well-suited for larger, stable applications, while **Java-based** configurations offer better refactoring tools and compile-time safety. 706 | 707 | - **Application Type Considerations**: Select the appropriate method based on the application's specifics - such as web-based apps or when flexibility for customizations is required. 708 | 709 | - **Startup Control**: Certain `ApplicationContext` implementations allow for custom startup modes. 710 |
711 | 712 | ## 11. What is _Aspect-Oriented Programming (AOP)_? 713 | 714 | **Aspect-Oriented Programming** (AOP) complements **Object-Oriented Programming** (OOP) by addressing **cross-cutting concerns**, like logging or security settings, that cut across disparate modules and classes. 715 | 716 | AOP achieves modularity by: 717 | 718 | - Identifying **cross-cutting concerns** 719 | - Specifying **join points** in the code, where these concerns can be applied 720 | - Defining **advice**, which provides actions to be taken at these points 721 | 722 | For example, you might have logging code scattered throughout your application, triggered at various points. With AOP, you can consolidate this logic separately, marking points in the code (e.g., method calls) where logging should occur. 723 | 724 | ### Core Concepts 725 | 726 | - **Aspect**: A module of classes containing related advice and join point definitions. 727 | 728 | - **Join Point**: A point in the execution of the application (such as a method call or exception being thrown) that can be targeted by advice. 729 | 730 | - **Pointcut**: A set of one or more join points targeted by a piece of advice. 731 | 732 | - **Advice**: The action that should be taken at a particular join point (e.g., the code to execute before a method is called). 733 | 734 | - **Introduction**: Allows adding new methods or attributes to existing classes dynamically. 735 | 736 | - **Weaving**: The process of linking aspects to the execution of an application. 737 | 738 | - **Compile-Time Weaving**: Modifications are applied at compile time. 739 | - **Load-Time Weaving**: The aspect is applied when the class is loaded, often by a special class loader. 740 | - **Run-Time Weaving**: Changes are made during the execution of the code. 741 | 742 | The three weaving mechanisms can be further categorized into four strategies: 743 | 744 | - **Singleton weaving**: The aspect is a singleton and is woven into the client at most once. 745 | - **Per-instance weaving**: The aspect is woven into each object before it is returned. 746 | - **Single-time weaving**: The aspect is woven into the client the first time it is instantiated. 747 | - **Combination-of-above weaving**: A combination of the above strategies is used to achieve weaving. 748 | 749 | - **Decoration**: Uses a **proxy** or **wrapper** to intercept method calls and apply cross-cutting concerns. 750 | 751 | - **Dynamic Proxy**: Java's `java.lang.reflect.Proxy` is often used. 752 | - **CGLIB**: A code generation library for high-performing and customized proxies. 753 | 754 | ### Benefits of AOP 755 | 756 | - **Modularity**: AOP allows you to isolate cross-cutting concerns, reducing code redundancy and increasing maintainability. 757 | - **Flexibility**: Concerns like security and auditing often require fine-grained control. AOP provides that. 758 | 759 | - **Simplicity**: The application's core components can remain clean and focused on their main tasks. 760 | 761 | ### AOP in Spring 762 | 763 | - In Spring, AOP is integrated using **proxies** and **aspect J annotations** or XML configurations. 764 | - Spring relies on a **proxy-based** system for AOP, using either standard Java interfaces for proxy creation or bytecode modification with CGLIB. 765 | - You can choose **declarative or programmatic** AOP configuration styles. 766 |
767 | 768 | ## 12. How does _Spring_ support _AOP_? 769 | 770 | **Spring** provides a powerful **Aspect-Oriented Programming (AOP)** framework. This framework simplifies the development process by enabling the separation of cross-cutting concerns from the main business logic. This leads to modular and more maintainable code. 771 | 772 | ### Core Concepts 773 | 774 | #### Aspect 775 | An **aspect** is a module encapsulating concerns such as logging or security. These typically cross-cut multiple application modules. 776 | 777 | #### Join Point 778 | A **join point** is a point during the execution of a program such as a method invocation. 779 | 780 | #### Advice 781 | The action taken by an aspect at a particular join point. Different types of advice include *before*, *after*, *around*, *after-returning*, and *after-throwing*. 782 | 783 | #### Pointcut 784 | A rule in AOP that defines the join points where advice should be applied. For example, you might specify that a particular advice applies to methods whose name begins with "get". 785 | 786 | #### Introduction 787 | The introduction allows adding new methods or attributes to a class. 788 | 789 | #### Target object 790 | The object being advised by one or more aspects. 791 | 792 | ### AOP Concepts in Practice 793 | 794 | - **Proxy**: Spring AOP uses JDK dynamic proxies or CGLIB to generate a proxy for the target object. The proxy provides an opportunity to intercept the method invocations to apply the aspects. Spring applies the most appropriate proxy type, based on the context and the configuration. 795 | 796 | - **Weaving**: This is the process of linking the aspects with the application objects. Weaving can be achieved at different points in the application life cycle, providing flexibility. Spring supports three weaving mechanisms: 797 | - **Compile-time weaving**: Aspects are incorporated into the application code during compilation. 798 | - **Load-time weaving**: Weaving takes place at the class loading time using a class loader to load the modified classes. 799 | - **Run-time weaving**: Weaving happens during runtime, either programmatically or using an agent. 800 | 801 | ### Code Example: AspectJ Around Advice 802 | 803 | Here is the Java code: 804 | 805 | ```java 806 | import org.springframework.context.annotation.Bean; 807 | import org.springframework.context.annotation.Configuration; 808 | import org.aspectj.lang.annotation.Aspect; 809 | import org.aspectj.lang.annotation.Around; 810 | import org.aspectj.lang.ProceedingJoinPoint; 811 | 812 | @Aspect 813 | @Configuration 814 | public class SecurityAspect { 815 | 816 | @Bean 817 | public SecurityManager securityManager() { 818 | return new SecurityManager(); 819 | } 820 | 821 | @Around("execution(* com.example.app.service.*.*(..))") 822 | public Object applySecurity(ProceedingJoinPoint joinPoint) throws Throwable { 823 | SecurityManager securityManager = securityManager(); 824 | if (securityManager.isAuthenticated()) { 825 | return joinPoint.proceed(); 826 | } else { 827 | throw new SecurityException("User is not authenticated."); 828 | } 829 | } 830 | } 831 | ``` 832 |
833 | 834 | ## 13. Can you explain a _Pointcut_ and an _Advice_ in _Spring AOP_? 835 | 836 | A **Pointcut** in Spring AOP defines the join points matched for advice and determines the regions in an application where cross-cutting concerns are applied. 837 | 838 | In AOP, a Pointcut serves as a **predicate** for identifying the locations in an application where advice is to be applied. These locations are primarily method executions but can also include field references and updates. 839 | 840 | Certain attributes are fundamental to Pointcuts. For example, the **scope** of the application and the type of join points, for instance, the Start of the Method of execution or even well within its body. 841 | 842 | ### Using Pointcuts 843 | 844 | To apply AOP in Spring, mark the points in your application where cross-cutting is required. From there, define methods using annotations such as `@Before`, `@After`, or `@Around` to apply the advice. 845 | 846 | ### Code Examples: Pointcuts & Advice 847 | 848 | Here is the Java code: 849 | 850 | ```java 851 | @Aspect 852 | @Component 853 | public class LoggingAspect { 854 | 855 | // Define Pointcuts 856 | @Pointcut("execution(* com.example.service.*.*(..))") 857 | public void serviceLayerExecution() {} 858 | 859 | @Pointcut("args(Long,..) && serviceLayerExecution()") 860 | public void serviceLayerMethodsWithLongArg() {} 861 | 862 | @Before("serviceLayerMethodsWithLongArg()") 863 | public void logServiceMethodWithLongArg(JoinPoint joinPoint) { 864 | System.out.println("Before method execution: " + joinPoint.getSignature().getName()); 865 | } 866 | } 867 | ``` 868 | 869 | In this example: 870 | 871 | - `serviceLayerExecution()`: Matches the execution of any public method in a class present in the `com.example.service` package. 872 | 873 | - `serviceLayerMethodsWithLongArg()`: Refines the previous pointcut, ensuring it only matches on methods with a Long parameter as the first argument. 874 | 875 | - `logServiceMethodWithLongArg()`: This is the advice that's applied before the defined join points. 876 | 877 | ### Aspect-Oriented Programming in Spring 878 | 879 | - **@AspectJ-style**: Employs aspect-oriented programming to define **Aspects**, The units that collect related **Pointcuts** and **Advices**. 880 | 881 | - **@Annotation-based**: Permits selection of join points using annotations on the relevant modules. This method does not involve any pointcut expressions or direct exposure of AspectJ. 882 | 883 | - **XML-based Configuration**: Flexibility for hooking up aspects in codebases without annotations. 884 | 885 | ### Type of Advices 886 | 887 | **Join Points**: The specific times during program execution when **Advices** execute. 888 | 889 | - **Before**: Runs the advice before the selected join point. 890 | 891 | - **After**: Executes the advice after the join point; applicable for both successful and failing conditions. 892 | 893 | - **Around**: Provides control over when and if the method proceeds to its natural execution. This enables advice to be run before and after the method execution. 894 | 895 | - **AfterReturning**: Only runs when the join point method is successfully completed. 896 | 897 | - **AfterThrowing**: Only applies when the join point method throws an exception. 898 | 899 | ### Additional Mechanisms to Aid Debugging 900 | 901 | - **This()**: Refers to the current executing object. 902 | 903 | - **Target()**: The target object for the method being advised. 904 | 905 | - **Bean()**: The bean that owns the method being advised. 906 | 907 | - **References to Execution Methods**: A shorthand for creating pointcuts. An example is `execution(public * com.example.SomeInterface.*(..))` to match the execution of any public method in classes implementing the `SomeInterface`. 908 |
909 | 910 | ## 14. What is a _Join Point_ in _Spring AOP_? 911 | 912 | A **Join Point** in **Spring AOP** represents a specific point during the execution of a program, which could be targeted for additional functionality, such as before, after, or around method calls. 913 | 914 | When a join point is intercepted by a Spring AOP advice, the advice can perform certain actions. The availability of join points differs across diverse AOP methodologies. For example, AspectJ provides more extensive join points than proxy-based AOP in Spring. 915 | 916 | ### Common Join Points 917 | 918 | - **Method Execution**: This join point signifies execution of a method. 919 | - **Method Call**: Denotes when the method is called from another location in the code. 920 | - **Class Initialization**: Marks when a class is initialized. 921 | - **Field Access**: Represents read or write actions on a field. 922 | - **Instance Construction**: Indicates the instantiation of an object through a constructor. 923 | 924 | These join points are consistent across AOP frameworks. 925 | 926 | ### AspectJ-Exclusive Join Points 927 | 928 | - **Executions Involving Annotated Methods**: Targets the execution of methods marked with a specific annotation. 929 | - **Executions in Specific Layers**: Directs actions to methods situated in defined layers or packages. 930 | 931 | ### Code Example: Join Points 932 | 933 | Here is the Java code: 934 | 935 | ```java 936 | public class SampleClass { 937 | private int sampleField; 938 | 939 | public void sampleMethod() { 940 | // Join Point: Method Execution or Method Call 941 | System.out.println("Sample Method Executed."); 942 | } 943 | 944 | public int getSampleField() { 945 | // Join Point: Field Access 946 | System.out.println("Getting Sample Field: " + sampleField); 947 | return sampleField; 948 | } 949 | 950 | public void setSampleField(int value) { 951 | // Join Point: Field Access 952 | System.out.println("Setting Sample Field: " + value); 953 | sampleField = value; 954 | } 955 | 956 | static { 957 | // Join Point: Class Initialization 958 | System.out.println("SampleClass Initialized."); 959 | } 960 | 961 | public SampleClass() { 962 | // Join Point: Instance Construction 963 | System.out.println("SampleClass Instance Created."); 964 | } 965 | } 966 | ``` 967 |
968 | 969 | ## 15. What is the difference between a _Concern_ and a _Cross-cutting Concern_ in _Spring AOP_? 970 | 971 | **Cross-cutting concerns** are aspects of software development that affect the entire application, yet are largely kept separate from the core business logic. This separation improves the modularity, maintainability, and reusability of the codebase. 972 | 973 | `Spring Aspect-Oriented Programming` (**AOP**) is tailored for managing cross-cutting concerns. 974 | 975 | While a "concern" is a more general term, referring to anything that requires the application's attention, a "cross-cutting concern" specifically relates to the aspects that cut across different modules or layers of a software system. 976 | 977 | ### Examples of Cross-Cutting Concerns 978 | 979 | - **Logging**: The need to log method invocations or business operations. 980 | - **Security**: Centralized control for authentication and authorization mechanisms. 981 | - **Caching**: Optimizing performance by caching the results of expensive operations. 982 | - **Exception Handling**: Providing a consistent way to handle exceptions across the application. 983 | 984 | The AOP approach of managing such concerns employs join points, pointcuts, and advice, and is separate from method-specific or local object concerns. 985 | 986 | ### Code Example: Cross-Cutting Concerns in Spring AOP 987 | 988 | Here is the Java code: 989 | 990 | **Bean Class:** 991 | 992 | ```java 993 | public class MyBook { 994 | private String bookName; 995 | 996 | public String getBookName() { 997 | return bookName; 998 | } 999 | public void setBookName(String bookName) { 1000 | this.bookName = bookName; 1001 | } 1002 | } 1003 | ``` 1004 | 1005 | **LogAspect:** 1006 | 1007 | ```java 1008 | @Aspect 1009 | public class LogAspect { 1010 | 1011 | @Before("execution(* MyBook.getBookName())") 1012 | public void logMethodName(JoinPoint joinPoint) { 1013 | System.out.println("Method invoked: " + joinPoint.getSignature()); 1014 | } 1015 | 1016 | @AfterReturning(pointcut = "execution(* MyBook.getBookName())", returning = "result") 1017 | public void logReturnValue(JoinPoint joinPoint, Object result) { 1018 | System.out.println("Returned: " + result); 1019 | } 1020 | 1021 | } 1022 | ``` 1023 | 1024 | **AppConfig:** 1025 | 1026 | ```java 1027 | @Configuration 1028 | @EnableAspectJAutoProxy 1029 | public class AppConfig { 1030 | 1031 | @Bean 1032 | public MyBook myBook() { 1033 | return new MyBook(); 1034 | } 1035 | 1036 | @Bean 1037 | public LogAspect logAspect() { 1038 | return new LogAspect(); 1039 | } 1040 | 1041 | } 1042 | ``` 1043 |
1044 | 1045 | 1046 | 1047 | #### Explore all 100 answers here πŸ‘‰ [Devinterview.io - Spring](https://devinterview.io/questions/web-and-mobile-development/spring-interview-questions) 1048 | 1049 |
1050 | 1051 | 1052 | web-and-mobile-development 1053 | 1054 |

1055 | 1056 | --------------------------------------------------------------------------------