Spring Interview Questions
1. Difference between the Spring framework and Spring Boot
- Spring Framework: A comprehensive Java-based framework for enterprise applications (DI, AOP, MVC, Transaction). It requires significant XML or Java configuration to set up.
- Spring Boot: An extension of the Spring Framework that focuses on RAD (Rapid Application Development). It provides auto-configuration and an embedded server (Tomcat/Jetty), removing the need for boilerplate configuration and external deployment. It works "out of the box".
2. What is dependency injection? Why do we need dependency injection? How does spring IOC container work?
- Dependency Injection (DI): A design pattern where dependencies (objects) are injected into a class rather than the class creating them itself (Inversion of Control - IoC).
- Why need it?
- Decoupling: Classes are not tightly coupled to specific implementations.
- Testability: Easy to mock dependencies for unit testing.
- Maintainability: Changes in implementation don't require changing client code.
- How Spring IoC Works: The IoC Container (ApplicationContext) scans configuration (XML/Annotations), instantiates beans, manages their lifecycle, and injects dependencies at runtime.
3. How to inject beans in spring? (Setter vs Constructor)
Methods:
1. Constructor Injection: Dependencies provided via constructor arguments.
2. Setter Injection: Dependencies provided via setter methods.
3. Field Injection: Using @Autowired directly on fields (Not recommended due to testing issues).
a. Setter vs. Constructor Injection: * Constructor: Best for mandatory dependencies. Ensures the object is in a valid state upon creation. Immutable dependencies (final). * Setter: Best for optional dependencies or circular dependencies.
b. How to make setter injection mandatory?
* Use @Autowired(required = true) (default is true) or the @Required annotation (deprecated). Practically, if a setter is autowired and the bean is missing, Spring throws an exception on startup.
4. How to configure/create beans in spring?
- XML Configuration:
<bean id="..." class="..."/> - Java-based Configuration:
@Configurationclass with@Beanmethods. - Annotation-based:
@Component(and stereotypes like@Service,@Repository) with Component Scanning (@ComponentScan).
5. Difference between BeanFactory and ApplicationContext?
- BeanFactory: The root interface for accessing the Spring container. Provides basic DI and lazy loading of beans.
- ApplicationContext: A sub-interface of BeanFactory. It adds enterprise-specific functionality:
- Eager loading of singleton beans (pre-instantiation).
- i18n support.
- Event publication.
- AOP integration.
- Standard usage: Always use
ApplicationContextunless memory is extremely limited.
6. Describe bean scopes that are supported by spring
a. Singleton vs Prototype: * Singleton (Default): One instance per Spring Container. Cached and reused. * Prototype: A new instance is created every time the bean is requested.
b. Is singleton bean thread safe? * No. Spring does not guarantee thread safety. If a singleton bean has mutable state (instance variables), it is not thread-safe. Stateless beans (services/DAOs) are usually thread-safe by design.
c. What’s the default bean scope? * Singleton.
d. How to define the scope of a spring bean?
* Use @Scope("prototype") or @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE).
7. Given a singleton bean A and a prototype bean B, how do we inject A into B? What will be the behaviors of the beans?
- Injection: Simply inject A into B normally (autowire).
- Behavior: Since B is prototype, a new B is created each time. A is singleton, so the same instance of A will be injected into every new instance of B. This works as expected.
8. Given a singleton bean A and a prototype bean B, how do we inject B into A? What will be the behaviors of the beans?
- Problem: A is created only once. B is injected into A at that time. Therefore, A will hold the same instance of B for its entire lifecycle, effectively making B act like a singleton inside A.
- Solution (Lookup Method / ObjectFactory): To get a new B every time A needs it:
- Inject
ObjectFactory<B>orProvider<B>and callgetObject(). - Use
@Lookupmethod injection. - Inject
ApplicationContextand callgetBean(B.class).
- Inject
9. What’s your understanding on @Autowired? How does Spring know which bean to inject? What’s the usage of @Qualifier?
- @Autowired: Marks a constructor, field, or setter to be autowired by Spring's dependency injection facilities.
- Mechanism:
- ByType: Checks if there is exactly one bean of the matching type.
- ByName: If multiple beans of the same type exist, it uses the field/parameter name to match the bean ID.
- @Qualifier: Used when multiple beans of the same type exist to resolve ambiguity. It explicitly specifies the bean name to inject (e.g.,
@Qualifier("myBean")).
10. What is circular dependency?
- Occurs when Bean A depends on Bean B, and Bean B depends on Bean A.
- Resolution:
- Constructor Injection: Fails with
BeanCurrentlyInCreationException. - Setter/Field Injection: Spring solves this for Singleton beans by injecting a partially constructed bean (early reference).
- @Lazy: Use
@Lazyon one of the constructor parameters to delay initialization.
- Constructor Injection: Fails with
11. What is the usage of @SpringBootApplication?
It is a convenience annotation that combines three annotations:
1. @Configuration: Marks the class as a source of bean definitions.
2. @EnableAutoConfiguration: Tells Spring Boot to start adding beans based on classpath settings (e.g., adding Tomcat if spring-boot-starter-web is present).
3. @ComponentScan: Tells Spring to look for other components/configurations in the current package and sub-packages.
12. What's the difference between @Component, @Repository & @Service?
- @Component: Generic stereotype for any Spring-managed component.
- @Service: Specialization of
@Componentfor the Service Layer (Business Logic). - @Repository: Specialization of
@Componentfor the Persistence Layer (DAO).
a. Functionality difference:
* Technically, they are interchangeable regarding bean creation.
* @Repository specific: It enables PersistenceExceptionTranslationPostProcessor, which translates database-specific checked exceptions (e.g., SQLException) into Spring's unchecked DataAccessException hierarchy.
* @Service specific: Currently mostly semantic, but good for AOP pointcuts.
13. How can you handle transactions in spring boot
- Use the @Transactional annotation on methods or classes.
- Spring uses AOP to create a proxy. It opens a transaction before the method starts and commits it after the method finishes.
- If a
RuntimeException(unchecked) is thrown, it rollbacks. Checked exceptions do not trigger rollback by default (needrollbackFor=Exception.class).
14. Describe Spring MVC (Need to mention DispatcherServlet)
Flow: 1. Request hits the DispatcherServlet (Front Controller). 2. DispatcherServlet consults HandlerMapping to find the correct Controller. 3. DispatcherServlet calls the Controller. 4. Controller executes business logic and returns a Model and View name. 5. DispatcherServlet resolves the view using ViewResolver. 6. The View is rendered and the response is sent back to the user.
15. What is ViewResolver in Spring?
- It maps logical view names (returned by the controller, e.g., "home") to actual view resources (e.g.,
/WEB-INF/views/home.jspor a Thymeleaf template).
16. Difference between @Controller and @RestController
- @Controller: Used for traditional Spring MVC. Returns a String (view name). To return JSON/XML, you need to add
@ResponseBodyto the method. - @RestController: A convenience annotation that combines
@Controllerand@ResponseBody. Every method returns domain objects directly (serialized to JSON/XML) instead of a view.
17. What is RestTemplate?
- A synchronous client to perform HTTP requests. It simplifies the interaction with RESTful services. (Note: In modern Spring,
WebClientis preferred for non-blocking scenarios, butRestTemplateis still widely used).
18. @RequestBody vs. @ResponseBody
- @RequestBody: Deserializes the HTTP request body (JSON/XML) into a Java Object.
- @ResponseBody: Serializes the return Java Object into the HTTP response body (JSON/XML).
19. @PathVariable vs. @RequestParam
- @PathVariable: Extracts values from the URI path. (e.g.,
/users/{id}->/users/123). Mandatory by default. - @RequestParam: Extracts values from query parameters. (e.g.,
/users?id=123).
20. How do you use Spring Repository?
- Define an interface extending
JpaRepository(orCrudRepository). - Spring Data JPA automatically implements the interface at runtime, providing CRUD methods (
save,findAll,findById) and generating queries from method names (e.g.,findByLastName).
21. What are different kinds of http methods? (POST vs PUT vs PATCH)
Methods: GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS.
a. POST vs PUT vs PATCH: * POST: Create a new resource. Non-idempotent. * PUT: Update/Replace a resource completely. Idempotent. (If the resource doesn't exist, it may create it). * PATCH: Update a resource partially. Non-idempotent (theoretically, though often implemented as idempotent).
22. Difference between SOAP vs. REST
| Feature | SOAP | REST |
|---|---|---|
| Protocol | Protocol (uses XML). | Architectural Style (uses HTTP). |
| Format | XML only. | JSON, XML, HTML, Plain Text (JSON is standard). |
| State | Stateful or Stateless. | Stateless. |
| Complexity | Heavyweight, strict standards (WSDL). | Lightweight, flexible. |
23. Is REST stateless?
- Yes. The server does not store any state about the client session. Every request must contain all the information needed to understand and process the request (e.g., including the authentication token).
24. Describe the RESTful principles.
- Client-Server: Separation of concerns.
- Stateless: No session state on server.
- Cacheable: Responses must define themselves as cacheable or not.
- Uniform Interface: Standardized resources (URIs, HTTP verbs).
- Layered System: Client doesn't know if it's connected to end server or intermediate.
- Code on Demand (Optional): Server can send executable code (JS).
25. How to validate the values of a request body? a. How does BindingResult work?
- Use Bean Validation (Hibernate Validator) annotations (e.g.,
@NotNull,@Size) on the DTO class. - Add @Valid or @Validated annotation to the
@RequestBodyparameter in the controller.
a. BindingResult:
* It is an object that holds the result of the validation and binding and contains errors that may have occurred. It must immediately follow the model object argument. If validation fails, errors are put into BindingResult instead of throwing an exception immediately (if BindingResult is present in method signature).
26. How to maintain user logged in using REST service
- Since REST is stateless, we don't use Server-Side Sessions (JSESSIONID).
- Use Tokens (JWT - JSON Web Tokens).
- Flow: User logs in -> Server verifies -> Server issues JWT -> Client stores JWT -> Client sends JWT in
Authorizationheader for subsequent requests -> Server validates JWT.
27. What is Spring AOP?
- Aspect-Oriented Programming. It allows separating cross-cutting concerns (logging, security, transaction management) from business logic.
- Key terms: Aspect (Class), Advice (Action), Pointcut (Where to apply), JoinPoint (Execution instance).
28. Talk about Spring Security
- A powerful, customizable authentication and access-control framework.
- Authentication: Verifying identity (Who are you?).
AuthenticationManager,UserDetailsService. - Authorization: Access control (What can you do?). Filter chains,
@PreAuthorize. - It uses a chain of Servlet Filters to intercept requests.
29. How is JWT used with Spring Security?
- Create a JWT Utility to generate and validate tokens.
- Create a JWT Authentication Filter (extends
OncePerRequestFilter). - In the filter: Extract token from header -> Validate token -> If valid, create
Authenticationobject and set it inSecurityContextHolder. - Add this filter before the
UsernamePasswordAuthenticationFilter.
30. What is unit testing vs integration testing?
- Unit Testing: Testing a single unit of code (method/class) in isolation. Dependencies are mocked. Fast.
- Integration Testing: Testing how different modules/layers work together (e.g., Controller + Service + DB). Uses actual Spring Context. Slower.
31. What do you use for testing? (Mockito)
- JUnit: For running tests and assertions.
- Mockito: A mocking framework to create mock objects and define their behavior (stubs) to isolate the unit under test.
- Spring Boot Test: (
@SpringBootTest,@MockBean) for integration support.
32. Describe some common annotations of Mockito.
- @Mock: Creates a mock instance of the class/interface.
- @InjectMocks: Creates an instance of the class under test and injects the mocks (annotated with @Mock) into it.
- @Spy: Creates a partial mock (calls real methods unless stubbed).
- @MockBean: (Spring specific) Adds a mock to the Spring ApplicationContext.
33. What’s the difference between doReturn and thenReturn?
when(mock.method()).thenReturn(value): The real method is called (for Spies), then the return value is overridden. Can throw exceptions if the real method has checks.doReturn(value).when(mock).method(): The real method is never called. Safer for Spies and void methods.
34. What are some tools that can be used to view test code coverage?
- JaCoCo (Java Code Coverage) is the most popular plugin for Maven/Gradle.
- IntelliJ IDEA built-in coverage runner.
35. What annotation do you use to quickly switch between different environments to load different configurations?
- @Profile("dev") / @Profile("prod").
- Active profile is set via
spring.profiles.activeproperty.
36. What is Jasypt?
- Java Simplified Encryption. It is a library used to encrypt sensitive information in configuration files (like DB passwords in
application.properties). Spring Boot reads the encrypted value (e.g.,ENC(...)) and Jasypt decrypts it at runtime.