Java Spring Interview Questions
153 questions with answers · Java Interview Guide
Spring Framework, Spring Boot, beans, scopes, dependency injection, annotations, and AOP. Essential for backend Java developer roles.
What Spring Scopes do you know
Singleton (one instance application-wide), Prototype (new per injection), Request (per HTTP request), Session (per user session), Application (application scope).
What is Bean
A Bean in Spring is a managed object created and maintained by the Spring IoC container with lifecycle methods and dependency injection capabilities.
What is the life cycle of Spring Beans
Spring Bean lifecycle: instantiation → property injection → BeanNameAware/BeanFactoryAware callbacks → BeanPostProcessor.postProcessBeforeInitialization → @PostConstruct/InitializingBean.afterPropertiesSet → BeanPostProcessor.postProcessAfterInitialization → ready for use → @PreDestroy/DisposableBean.destroy on shutdown.
What is Spring context
Spring context (ApplicationContext) is a container that manages bean lifecycle, dependency injection, and provides access to beans and resources defined in configuration.
What scopes do beans have
Singleton (one instance per container), Prototype (new instance each time), Request, Session, Application, and WebSocket scopes.
What is the difference between Dependency Injection and Inverhuron of Control
Dependency Injection is the mechanism of providing dependencies; Inversion of Control is the broader principle where the framework controls object creation and lifecycle.
Why do you need Spring Framework
Spring provides declarative transaction management, AOP, dependency injection, and reduces boilerplate, enabling loose coupling and easier testing.
What is Bean, what role does Spring play
A Bean is a reusable Java component following JavaBean conventions; Spring manages Bean lifecycle, dependency injection, and configuration through its IoC container.
What are the options for Dependensky Injection
Constructor injection, setter injection, and field injection (@Autowired) are the main options for dependency injection in Spring.
What is Dependency Injection in Spring
Dependency Injection is a design pattern where Spring automatically provides object dependencies rather than objects creating them themselves, promoting loose coupling.
What is Spring Boot and what is its main advantage
Spring Boot is a framework that simplifies Spring application setup with auto-configuration and embedded servers; main advantage is reduced boilerplate and faster development.
What kind of Bean Scope do you know
Singleton (one per container), Prototype (new instance per request), Request (one per HTTP request), Session (one per session), and Application (one per ServletContext).
What is Springscope
Scope in Spring defines the lifecycle and visibility of beans,where they're created and when they're destroyed within the application context.
What is Spring Boot for
Spring Boot provides rapid development with auto-configuration, embedded servers, and opinionated defaults, eliminating manual XML configuration and setup overhead.
Have you heard anything about Spring MVC
Spring MVC is a web framework for building RESTful and traditional web applications using the Model-View-Controller pattern with servlet-based request handling and routing.
What does Dependency Injection give us
DI provides loose coupling, testability, and maintainability by injecting dependencies rather than hardcoding them, allowing easier mocking and configuration management.
What is the difference between IOC and Dependency Injection
IoC is the broader principle where the framework controls object lifecycle; Dependency Injection is a specific IoC implementation where dependencies are provided to objects.
What can be returned data types in Spring MVC
Spring MVC can return String (view name), ModelAndView, ResponseEntity, Map, @ResponseBody annotated objects (JSON/XML), and void with direct response writing.
Can it turn out so that there is no controller in the context
Yes, if you use @Service or @Repository without any HTTP mapping annotations, or if you use purely backend services like data processors, schedulers, or message consumers.
What we need to make Spring MVC earn
To use Spring MVC you need DispatcherServlet configured, at least one @Controller or @RestController bean, handler mappings, and a servlet container like Tomcat.
What is Scope
Scope defines the lifecycle of a bean: Singleton (one per context), Prototype (new per request), Request (per HTTP request), Session (per user session), Application (per ServletContext).
What is a context
Context is the Spring ApplicationContext container that holds all bean definitions, manages their lifecycle, performs dependency injection, and provides access to configured beans.
How dependency Injection can be applied to Spring Bean
Spring Bean dependency injection is applied via @Autowired constructor injection (preferred), setter injection with @Autowired, or field injection, resolved by type and qualified with @Qualifier if needed.
What is http type
HTTP types (methods) include GET (retrieve), POST (create), PUT (replace), PATCH (partial update), DELETE (remove), and OPTIONS (describe communication options).
How Dispatcher Servlet "understands" which method to call
DispatcherServlet uses RequestMappingHandlerMapping to match incoming HTTP requests to controller methods based on @RequestMapping annotations, HTTP method, and URL patterns.
As a client can understand what came to the browser from the server
The client understands server response through HTTP headers (Content-Type, Content-Length) and the response body containing HTML, JSON, or XML parsed by the browser or client library.
Why REST is needed
REST provides a stateless, scalable architecture for building distributed systems using standard HTTP methods, making APIs simple, cacheable, and language-agnostic.
What is the difference between Request Mapping and Put Mapping
@RequestMapping handles all HTTP methods (GET, POST, PUT, DELETE), while @PutMapping is specifically for PUT requests; @PutMapping is more explicit and preferred for REST design.
What Scope can be used for any application
Singleton scope is used for any application as the default in Spring; it creates one bean instance per Spring container shared across the entire application.
Request We can use in all Spring applications
Request scope can be used in all Spring applications as it creates a new bean instance for each HTTP request.
How do you use Dependency Injection
Dependency Injection inverts control by allowing Spring container to automatically inject dependencies into beans through constructor, setter, or field injection based on type or qualifier.
What IOC implementations do you know
IOC implementations include Spring IoC, PicoContainer, Guice, and CDI; Spring IoC is the most widely used for enterprise applications.
What is Spring IOC container in Spring.
Spring IoC container manages bean lifecycle, dependency injection, and object creation; implementations include ApplicationContext and BeanFactory with ApplicationContext preferred for production.
What areas of visibility in Spring you know
Visibility/access areas in Spring: public (accessible everywhere), protected (same package and subclasses), package-private (same package only), private (class only).
What types of implementation of addiction do you know
Dependency injection types: Constructor Injection (immutable, testable), Setter Injection (flexible, circular dependency prone), Field Injection (@Autowired, harder to test), and Method Injection.
Tell me what is Inversion of Control
Inversion of Control transfers control of object lifecycle and dependencies from the application to a container, allowing loose coupling and easier testing.
What is Spring Framework
Spring Framework is a lightweight, open-source Java framework providing IoC, AOP, transaction management, and MVC support for building enterprise applications.
Where it is more convenient to use Java configuration, and where is XML configuration
Java configuration (@Configuration, @Bean) is preferred for complex logic and type-safety; XML configuration suits large teams and external configuration changes without recompilation.
What is Spring IOC container in Spring.
Spring IOC container manages bean lifecycle and dependency injection, instantiating objects and wiring dependencies based on configuration metadata from XML, annotations, or Java classes.
What areas of visibility in Spring you know
Bean scopes in Spring include singleton (one instance per context), prototype (new instance per request), request, session, application, and websocket scopes.
What types of implementation of addiction do you know
Dependency injection types are constructor injection, setter injection, and field injection; constructor injection is preferred for mandatory dependencies.
Tell me what is Inversion of Control
Inversion of Control transfers control of object creation and lifecycle management from application code to a container, reducing coupling and improving testability.
What is Spring Framework
Spring Framework is a lightweight, modular Java framework providing IoC, AOP, transaction management, web MVC, and data access abstractions.
Where it is more convenient to use Java configuration, and where is XML configuration
Java configuration suits complex logic and type-safety; XML is better for external configuration changes without recompilation and legacy systems.
What configuration would be removed
The question is unclear; if asking what configuration to remove: redundant bean definitions or unused profiles should be cleaned up.
Which of the configuration, XML, Java Annotation, you prefer more
Annotations are preferred for modern Spring apps due to cleaner code and less boilerplate; XML for external configuration in large enterprises.
What configuration will be more priority: XML, Java or Annotation
Priority order: Annotation (highest) overrides Java configuration, which overrides XML (lowest); beans defined in multiple places follow this precedence.
Now in Spring it is not necessary to indicate the AbowireD annotation, why is it so
@Autowired is optional in Spring 4.3+ because constructor injection is auto-wired by default; field/setter injection still requires explicit annotation.
How to create a controller in Spring
Create a Spring controller using @Controller or @RestController annotation on a class with @RequestMapping or @GetMapping/@PostMapping methods.
How can you create Servlett in Spring'e
Servlets in Spring are created as DispatcherServlet in web.xml or auto-configured via ServletRegistrationBean in Java config; Spring doesn't directly create servlets.
How the context works
Spring context (ApplicationContext) loads bean definitions, manages beans, resolves dependencies, and provides access to beans via getBean() method.
Is it possible to create two singleton in Spring.
Yes, you can create multiple singletons in Spring by defining multiple bean definitions with scope='singleton'; each bean name is a distinct singleton instance.
How many contexts can be
Spring supports multiple contexts: root ApplicationContext (beans shared across dispatchers) and child DispatcherServlet contexts (web-specific beans).
What does the SCAN component do
SCAN in Spring (via @ComponentScan or XML) automatically discovers and registers @Component, @Service, @Repository, @Controller annotated classes as beans.
What is the difference between Filters, Interceptors, and Listeners in Spring
Filters operate on request/response layer pre/post servlet, Interceptors wrap controller methods via AOP, Listeners react to application lifecycle events.
What is the difference between the component and bina
Both register beans in the container. @Component is generic; @Bean is explicit factory method registration offering fine-grained control.
What is the difference between Spring Component, Repository and Service Abstracts
@Component is generic; @Repository adds persistence exception translation; @Service indicates business logic layer and improves code semantics.
What is the life cycle of an object that creates Spring
Bean instantiation → setter/constructor injection → @PostConstruct → ready for use → @PreDestroy → destruction.
What is the difference between authentication and authorization
Authentication verifies identity (who you are via credentials), Authorization checks permissions (what you can access via roles/authorities).
What is JWT for
JWT encodes user identity and claims in a signed token, enabling stateless authentication and authorization without server-side session storage.
As if organized the Delete method
@DeleteMapping on controller method triggers service delete logic, which calls repository delete, executed as SQL DELETE statement.
How SOAP differs from REST
SOAP uses XML over HTTP with strict contracts and WS-* standards; REST uses JSON/HTTP verbs (GET/POST/PUT/DELETE) for stateless, cacheable operations.
How to write a web application on Java
Use Spring Boot with Spring Web starter, define @RestController endpoints, inject @Service beans, configure application.properties, deploy as JAR or WAR.
Why do you need a springs
Spring provides IoC container for dependency injection, declarative transaction management, AOP for cross-cutting concerns, and reduces boilerplate code compared to plain Java.
What is the BEAN annotation for
@Bean annotation registers a method's return value as a Spring bean in the application context; typically used in @Configuration classes.
What is the difference between RestController from Controller
@RestController returns JSON/XML directly (combines @Controller + @ResponseBody); @Controller returns view names for template rendering.
How to quickly make a rest service
Use Spring Boot with @RestController, @GetMapping/@PostMapping annotations, and Spring Data JPA for entities,minimal configuration produces a working REST service.
Why do you need a springs
Spring provides dependency injection, aspect-oriented programming, and declarative transaction management, reducing boilerplate and improving modularity.
What is the BEAN annotation for
@Bean annotation indicates a method produces a bean object managed by Spring container, typically used in @Configuration classes.
What is the difference between RestController from Controller
RestController combines @Controller and @ResponseBody, returning JSON/XML directly; Controller returns view names for template rendering.
How to quickly make a rest service
Use @SpringBootApplication with @RestController and @GetMapping/@PostMapping annotations on methods returning JSON; Spring auto-configures and exposes REST endpoints via embedded Tomcat.
The difference in annotations Service, Repository, Controller
@Service marks business logic layer, @Repository handles data access and Spring translates DB exceptions, @Controller returns views while @RestController returns JSON/XML data.
What types of proxies do you know
JDK proxies (interface-based), CGLIB proxies (subclass-based), and AspectJ proxies; Spring uses JDK by default, falls back to CGLIB if no interface.
How to create singleton-tin when starting a Spring application
Use @Bean with @Scope("singleton") or @Component with default scope; Spring creates single instance per ApplicationContext.
What types of proxies do you know
Proxies in Spring include JDK dynamic proxies for interfaces and CGLib proxies for classes; used for AOP, transactions, and cross-cutting concerns.
How to create singleton-tin when starting a Spring application
Create singleton in Spring using @Bean with default scope (singleton) in @Configuration class, or use @Component/@Service with default singleton scope.
What projects did you do using Spring
I developed REST APIs with Spring Boot, banking transaction systems using Spring Data JPA, and microservices with Spring Cloud for deployment.
Tell the structure of Framework Collection
Collection interface hierarchy: Collection (List, Set, Queue), Map. List (ArrayList, LinkedList), Set (HashSet, TreeSet), Queue (PriorityQueue, Deque).
What are the methods of configuration Spring applications
XML configuration, Java annotations (@Configuration, @Bean), properties files, and YAML for Spring Boot applications.
Where the Bean annotation is used
@Bean marks methods returning Spring-managed objects; @Component, @Service, @Repository, @Controller are stereotype annotations for class-level bean registration.
What is the difference between RestController and Controller
@RestController returns JSON/XML directly; @Controller returns view names with model data for template rendering.
What is the difference in repository annotations, Component, Controller, Service
@Repository (DAO pattern), @Component (generic bean), @Controller (web layer), @Service (business logic layer) - semantically equivalent but contextually meaningful.
Where could Prototype be used
Prototype scope in Spring creates a new instance per request; used when you need stateful, non-shared objects or when multiple concurrent clients need isolated instances.
Which default Scope is used in Spring
The default scope in Spring is Singleton, meaning one instance per application context.
Tell the structure of Framework Collection
Spring Framework Collection consists of core containers (Core, Beans, Context) and supporting modules (AOP, Data, Web, Security) organized in a layered architecture.
What are the methods of configuration Spring applications
Spring applications can be configured via XML files (bean definitions), Java annotations (@Component, @Bean), or Java-based configuration classes (@Configuration).
Where the Bean annotation is used
@Bean marks methods that produce Spring-managed beans; used in @Configuration classes to instantiate and configure objects with fine-grained control.
What is the difference between RestController and Controller
@RestController combines @Controller + @ResponseBody, auto-serializing return values to JSON; @Controller requires explicit response serialization.
What is the difference in repository annotations, Component, Controller, Service
@Repository marks data access layer with exception translation; @Component is generic stereotype; @Controller for web handlers; @Service for business logic.
Where could Prototype be used
Prototype scope in Spring creates new bean instance for each request; used for stateful beans requiring fresh instances.
Which default Scope is used in Spring
Request scope is default in Spring; beans are created per HTTP request and destroyed after response, though Singleton scope is default for ApplicationContext beans.
Where and when used Prototype
Prototype scope in Spring creates new bean instance for each injection point; used when stateful beans are needed, unlike Singleton which shares single instance across application.
What will happen if in ApplicationContext you try to get the same bin
Getting the same bean from ApplicationContext returns the same singleton instance by default; if scope is 'prototype', a new instance is created each time.
What will happen if in ApplicationContext you try to get the same bin
Getting the same bean from ApplicationContext returns the same instance if it's a singleton scope (default), ensuring consistency across the application.
Where and when used Prototype
Prototype scope is used when you need a new instance created each time the bean is requested, useful for stateful beans or thread-safe objects.
Which default Scope is used in Spring
The default scope in Spring is Singleton, which creates one instance per Spring container and reuses it throughout the application lifecycle.
Where could Prototype be used
Prototype scope is used for stateful beans, request-scoped data objects, and scenarios requiring thread isolation or independent object instances.
What is the difference in repository annotations, Component, Controller, Service
Component is a generic stereotype; Service marks business logic beans; Repository marks data access layer beans; Controller marks web request handlers,semantically identical but convey intent.
What is the difference between RestController and Controller
RestController combines @Controller and @ResponseBody, automatically serializing return values to JSON/XML; Controller requires explicit @ResponseBody or view resolution.
Where the Bean annotation is used
@Bean is used on methods in @Configuration classes to explicitly define and configure beans with complex initialization logic.
What are the methods of configuration Spring applications
Spring applications can be configured via XML files, Java classes with @Configuration, or annotations with component scanning and @SpringBootApplication.
Tell the structure of Framework Collection
Spring Collection framework structure: Collection (List, Set, Queue) and Map interfaces with implementations like ArrayList, HashSet, HashMap, providing different performance characteristics.
What the largest project did you do using Spring
I developed a multi-tenant SaaS platform with Spring Boot, microservices, JPA/Hibernate, Redis caching, and REST APIs serving 10k+ concurrent users.
How to create singleton-tin when starting a Spring application
Create a singleton by using the default Singleton scope in Spring or by implementing eager initialization with @Bean or @PostConstruct in ApplicationContext startup.
What types of proxies do you know
Spring uses JDK dynamic proxies (for interfaces) and CGLIB proxies (for classes) for AOP, aspect weaving, and cross-cutting concerns like transactions.
The difference in annotations Service, Repository, Controller
Service, Repository, and Controller are semantically equivalent @Component stereotypes; Service indicates business logic, Repository indicates data access, Controller indicates web request handling.
How to quickly make a rest service
Create a REST service quickly using @SpringBootApplication, @RestController with @RequestMapping methods, @Autowired dependencies, and run SpringApplication.run() to auto-configure embedded Tomcat.
What is the difference between RestController from Controller
@RestController combines @Controller and @ResponseBody, automatically serializing returned objects to JSON/XML without needing explicit view resolution.
What is the BEAN annotation for
@Bean is a method-level annotation that defines a Spring-managed bean; the method's return value is registered as a bean in the application context.
Why do you need a Spring Framework
Spring provides dependency injection, aspect-oriented programming, transaction management, and declarative security, reducing boilerplate and improving maintainability.
How to write a web application on Java
Use @SpringBootApplication on main class, define @RestController endpoints with @GetMapping/@PostMapping methods, configure application.properties, and run the Spring Boot app.
How SOAP differs from REST
SOAP is XML-based, protocol-agnostic, and contract-driven with WSDL; REST is resource-oriented over HTTP, uses JSON, and is stateless with simpler URLs.
How to write a Delete method
Use @DeleteMapping annotation on a method that calls delete logic via repository; method returns void or ResponseEntity with appropriate HTTP status.
What is JWT for
JWT (JSON Web Token) is a stateless authentication mechanism that encodes user claims in a signed token, allowing secure API requests without server-side sessions.
What is the difference between authentication and authorization
Authentication verifies who you are (login credentials), while authorization determines what resources you can access (roles/permissions).
What is the life cycle of an object that creates Spring
Spring bean lifecycle: instantiation → setter injection → BeanPostProcessor.postProcessBeforeInitialization → @PostConstruct/init-method → postProcessAfterInitialization → usage → @PreDestroy/destroy-method.
What is the difference between Spring Component, Repository and Service Abstracts
@Component is generic, @Repository is for DAO/database operations, @Service is for business logic; they're semantically equivalent but indicate intent and enable specialized handling.
What is the difference between the component and bina
@Component and @Bean both create Spring beans, but @Component is class-level annotation for auto-detection via classpath scanning, while @Bean is method-level for manual configuration.
What is the difference between Filters, Interceptors, and Listeners in Spring
Filters operate at servlet level, Interceptors at Spring MVC level with access to request/response/handler, and Listeners react to application events; execution order differs.
What does the SCAN component do
@ComponentScan tells Spring where to look for @Component/@Service/@Repository annotations; it auto-registers found classes as beans in the application context.
How many contexts can be in Spring
Spring typically has two contexts: ApplicationContext (parent, for services/repositories) and WebApplicationContext (child, for controllers/web beans).
Is it possible to create two singleton in Spring.
No, Spring enforces singleton by design; you can create multiple instances only by using prototype scope with @Scope("prototype").
How the context works in Spring
Spring ApplicationContext loads bean definitions from configuration sources (XML/annotations/Java config), instantiates beans, injects dependencies, and manages their lifecycle.
How can you create Servlett in Spring'e
Create a Servlet by implementing ServletRegistrationBean or using @WebServlet annotation with Spring Boot's ServletRegistrationBean for custom servlet registration.
How to create a controller in Spring
Use @RestController class annotation with @RequestMapping or @GetMapping/@PostMapping method annotations; Spring auto-detects and registers it as a bean.
Now in Spring it is not necessary to indicate the AbowireD annotation, why is it so
Constructor injection is now preferred over @Autowired; Spring automatically injects dependencies via constructors without explicit annotation, improving testability and avoiding NullPointerException.
What configuration will be more priority: XML, Java or Annotation
Annotation > Java Config > XML; annotations are processed first during component scanning, Java config overrides them, and XML has lowest priority if all present.
Which of the configuration, XML, Java Annotation, you prefer more
Java annotations preferred; they're cleaner, type-safe, and eliminate XML verbosity while maintaining compile-time validation.
What configuration would be removed
XML configuration is largely removed in favor of annotations and Java config; Spring Boot auto-configuration makes manual bean definition obsolete.
Where it is more convenient to use Java configuration, and where is XML configuration
Java config for complex conditional beans and programmatic setup; XML for large legacy projects where centralized config is preferred.
What is Spring Framework
Spring Framework is a lightweight, open-source IoC container providing dependency injection, AOP, transaction management, and integrated MVC/data access layers.
Tell me what is Inversion of Control
IoC inverts control flow: framework manages object creation and wiring instead of the application; dependencies are pushed into objects rather than pulled.
What types of implementation of addiction do you know
Constructor injection (immutable, testable), setter injection (flexible, optional), and field injection (simple but less testable).
What areas of visibility in Spring you know
Bean scope visibility includes singleton (app-wide), prototype (new per request), request (per HTTP request), session (per user), and application (ServletContext level).
What is Spring IOC container in Spring.
Spring IoC container instantiates, configures, and manages beans; it reads configuration metadata and handles dependency resolution and lifecycle management.
What IOC implementations know
ApplicationContext and BeanFactory; ApplicationContext is the primary implementation with added features like event publishing and AOP.
How do you use Dependency Injection
Apply via constructor parameters, setter methods, or @Autowired/@Inject annotations; container resolves dependencies at runtime based on type or name.
Request We can use in all Spring applications
Request scope is specific to web applications; not all Spring applications are web-based, so it's not universally applicable.
What Scope can be used for any application
Singleton scope works in any application; it's the default and creates one instance per container for the entire application lifetime.
What is the difference between Request Mapping and Put Mapping
@RequestMapping maps HTTP requests to handler methods with flexible HTTP methods; @PutMapping is a shortcut for PUT requests only.
Why REST is needed
REST enables scalable, stateless client-server communication using HTTP standards; provides clear separation of concerns and cacheable, interoperable APIs.
As a client can understand what came to the browser from the server
Client checks HTTP response headers (Content-Type) and status codes; Content-Type indicates data format (JSON, XML), status code indicates result success/failure.
How Dispatcher Servlet "understands" which method to call
DispatcherServlet uses HandlerMapping to match request URL to controller methods, then invokes the appropriate handler via reflection based on path patterns.
What is http type
HTTP methods: GET (retrieve), POST (create), PUT (update), DELETE (remove), PATCH (partial update); define operation semantics on resources.
How dependency Injection can be applied to Spring Bean
Constructor injection (preferred), setter injection via @Autowired, field injection via @Autowired, or interface-based injection.
What is a context
Context is the ApplicationContext instance that holds bean definitions, manages lifecycle, resolves dependencies, and provides access to beans in the application.
What is Scope
Scope defines bean lifecycle and visibility: singleton (one per container), prototype (new per request), request/session (web-specific), application (ServletContext).
What we need to make Spring MVC earn
Spring MVC requires DispatcherServlet configured in web.xml or via WebApplicationInitializer, controller beans in context, view resolver, and handler mappings.
Can it turn out so that there is no controller in the context
No, DispatcherServlet must be present in the context as it's the central component that routes all requests in Spring MVC.
What can be returned data types in Spring MVC
Controllers can return String (view name), ModelAndView, Model, View, ResponseEntity, @ResponseBody with any serializable object, or void.
What is the difference between IOC and Dependency Injection
IoC is the principle of inverting control flow where framework manages object creation; Dependency Injection is the mechanism implementing IoC by injecting dependencies.
What does Dependency Injection give us
DI promotes loose coupling, testability, reusability, and centralized configuration management, making code more maintainable and flexible.
Have you heard anything about Spring MVC
Spring MVC is a framework for building web applications following MVC pattern with request/response handling, interceptors, validators, and view resolution.
Knowing the answers is half the battle
The other half is explaining them clearly under pressure.
Try a free mock interviewarrow_forward