Top 100 spring questions and answers, crack any java spring interview
1. What is Spring Framework?
Definition:
Spring is an open-source, lightweight Java framework designed to simplify enterprise application development. It promotes loose coupling through Dependency Injection (DI) and provides comprehensive infrastructure support for developing Java applications.
Features:
- Dependency Injection
- Aspect-Oriented Programming (AOP)
- Declarative transaction management
- MVC Web Framework
- Integration with frameworks like JPA, Hibernate
2. What is Inversion of Control (IoC)?
Definition:
IoC is a design principle where the control of object creation and dependency resolution is shifted from the application code to a container (like Spring).
Example:
@Component
public class Vehicle {
public void start() {
System.out.println("Vehicle started");
}
}
@Component
public class Driver {
@Autowired
private Vehicle vehicle;
public void drive() {
vehicle.start();
}
}
In this example, Spring injects the Vehicle object into the Driver object, not manually.
3. What is Dependency Injection (DI)?
Definition:
DI is the process of providing an object’s dependencies externally rather than creating them inside the class.
Types:
- Constructor Injection
- Setter Injection
- Field Injection (not recommended for testing)
Example (Constructor Injection):
@Component
public class Engine {
public void run() {
System.out.println("Engine running...");
}
}
@Component
public class Car {
private final Engine engine;
@Autowired
public Car(Engine engine) {
this.engine = engine;
}
public void move() {
engine.run();
}
}
4. Constructor vs Setter Injection
- Constructor: Immutable, best for required dependencies.
- Setter: Flexible, good for optional dependencies.
Constructor Example:
@Autowired
public Car(Engine engine) {
this.engine = engine;
}
Setter Example:
@Autowired
public void setEngine(Engine engine) {
this.engine = engine;
}
5. Field Injection vs Setter Injection
- Field: Easy to write, but hard to test.
- Setter: More testable, supports optional injection.
Field Injection (Not ideal):
@Autowired
private Engine engine;
6. Difference Between @Component, @Service, @Repository, @Controller
All these annotations register a class as a Spring Bean.
@Component: Generic stereotype.@Service: Marks a service layer class.@Repository: DAO layer, enables exception translation.@Controller: Used in MVC for handling HTTP requests.
Example:
@Service
public class UserService {
public String getUser() {
return "Ved";
}
}
7. What is @Autowired?
Definition:
Used to automatically wire dependencies by type (and optionally by name).
Example:
@Component
public class Bike {
@Autowired
private Engine engine;
}
Options:
@Autowired(required=false)- Used with
@Qualifierfor multiple beans.
8. What is @Qualifier?
Definition:
Used to resolve ambiguity when multiple beans of the same type exist.
Example:
@Component("dieselEngine")
public class DieselEngine implements Engine {}
@Component("petrolEngine")
public class PetrolEngine implements Engine {}
@Component
public class Car {
@Autowired
@Qualifier("petrolEngine")
private Engine engine;
}
. What are Bean Scopes in Spring?
Definition:
A bean’s scope defines the lifecycle and visibility of the bean in the Spring container.
Types:
singleton: Default. One shared instance.prototype: New instance per injection.- Web scopes:
request,session,application
Example:
@Component
@Scope("prototype")
public class Toy {
public Toy() {
System.out.println("New Toy created");
}
}
10. What is Lazy Initialization?
Definition:
Delays the creation of a bean until it’s first used.
Example:
@Component
@Lazy
public class HeavyComponent {
public HeavyComponent() {
System.out.println("HeavyComponent initialized");
}
}
Without @Lazy, this would be instantiated at startup.
11. What is the lifecycle of a Spring Bean?
- Bean instantiation
- Property population
setBeanName(),setBeanFactory(),setApplicationContext()(Aware interfaces)@PostConstructorafterPropertiesSet()(init phase)- Bean ready for use
@PreDestroyordestroy()(destroy phase)
Example:
@Component
public class MyBean implements InitializingBean, DisposableBean {
@PostConstruct
public void init() {
System.out.println("PostConstruct");
}
@PreDestroy
public void cleanup() {
System.out.println("PreDestroy");
}
@Override
public void afterPropertiesSet() {
System.out.println("InitializingBean logic");
}
@Override
public void destroy() {
System.out.println("DisposableBean logic");
}
}
12. What is the difference between ApplicationContext and BeanFactory?
BeanFactory: Basic container, lazy loading.ApplicationContext: Advanced container, supports:- Event propagation
- AOP
- Internationalization
- Eager loading
13. What is the use of @PostConstruct and @PreDestroy?
@PostConstruct: Executes after dependency injection is done.@PreDestroy: Executes before the bean is removed from the container.
14. How to make a bean singleton or prototype?
Use @Scope.
@Component
@Scope("prototype")
public class MyPrototypeBean {}
15. What is the role of @Configuration and @Bean?
@Configuration: Marks a class with bean definitions.@Bean: Declares a bean method.
@Configuration
public class AppConfig {
@Bean
public Car car() {
return new Car();
}
}
16. How to inject values from a property file?
Use @Value and @PropertySource.
@Configuration
@PropertySource("classpath:app.properties")
public class AppConfig {
@Value("${app.name}")
private String appName;
}
17. What is the default bean scope in Spring?
- Singleton — one instance per container.
18. What is the difference between Singleton and Prototype scope?
| Feature | Singleton | Prototype |
|---|---|---|
| Lifecycle | Managed fully | Only instantiation |
| Reuse | Yes | No |
| Garbage Col. | Done by Spring | Client responsibility |
19. What are the different ways to configure Spring beans?
- XML-based
- Annotation-based
- Java-based (
@Configuration)
20. How to make a class aware of its Spring container?
Implement ApplicationContextAware or use @Autowired ApplicationContext.
21. What is AOP in Spring?
Definition: aspect oriented programmin
AOP allows separation of cross-cutting concerns (like logging, security, transactions) from business logic.
22. What are the key concepts of Spring AOP?
- Aspect: A class that contains advice.
- Join Point: A point during program execution (e.g., method call).
- Advice: Action taken (e.g., before method executes).
- Pointcut: Expression to match join points.
- Weaving: Linking aspects with other application types.
23. What are the types of advice in Spring AOP?
@Before: Runs before method@After: Runs after method (regardless of outcome)@AfterReturning: Runs after successful method execution@AfterThrowing: Runs after an exception@Around: Controls method execution
Example:
@Aspect
@Component
public class LoggingAspect {
@Before("execution(* com.example.service.*.*(..))")
public void logBefore() {
System.out.println("Before method execution");
}
}
24. What is the difference between Spring AOP and AspectJ?
| Feature | Spring AOP | AspectJ |
|---|---|---|
| Type | Proxy-based | Compile-time/weaving |
| Use Case | Simple AOP | Advanced AOP (e.g., fields) |
| Dependency | Spring only | Requires AspectJ tools |
25. How to enable AOP in Spring?
Use @EnableAspectJAutoProxy.
@Configuration
@EnableAspectJAutoProxy
public class AppConfig {}
26. What is @Transactional annotation?
Marks methods/classes as transactional (rollback on failure, commit on success).
@Transactional
public void createUser(User user) {
userRepository.save(user);
}
27. What is Transaction Propagation in Spring?
Defines how transactions relate to each other.
| Type | Description |
|---|---|
| REQUIRED | Join existing or create new |
| REQUIRES_NEW | Always create new |
| SUPPORTS | Join if exists, else run non-transactional |
| MANDATORY | Must have existing transaction |
| NEVER | Must not run in a transaction |
8. What is the default rollback behavior of @Transactional?
Rolls back on unchecked (RuntimeException) and Errors by default.
To rollback on checked exception:
@Transactional(rollbackFor = Exception.class)
29. What is the difference between @Transactional at class and method level?
- Class level: Applies to all methods.
- Method level: Overrides class-level for that method.
30. Can we have multiple transactions in a single service?
Yes. Use different methods with different @Transactional settings. But Spring proxy may not work for self-invocation (needs external call).
31. What is transaction isolation?
Defines how transaction integrity is visible to other transactions (e.g., READ_COMMITTED, SERIALIZABLE).
@Transactional(isolation = Isolation.READ_COMMITTED)
32. What is the default transaction isolation level in Spring?
- Typically READ_COMMITTED (depends on DB).
33. What is transaction timeout in Spring?
Timeout in seconds before rollback occurs.
@Transactional(timeout = 30)
34. What is the use of @EnableTransactionManagement?
Enables Spring’s annotation-driven transaction management.
@Configuration
@EnableTransactionManagement
public class TxConfig {}
35. What is PlatformTransactionManager?
Interface that Spring uses to manage transactions across different platforms (JPA, JDBC, etc.).
36. What is the difference between programmatic and declarative transaction management?
| Type | Description |
|---|---|
| Declarative | Uses @Transactional (recommended) |
| Programmatic | Manual transaction management using TransactionTemplate |
37. How can AOP be used for logging?
Create an @Aspect class and log before/after method calls.
@Before("execution(* com.example.*.*(..))")
public void logBefore() {
System.out.println("Method is about to execute");
}
38. What are the limitations of Spring AOP?
- Works only with public methods
- Based on proxies, cannot advise internal calls
- No field-level interception
39. What is JoinPoint and ProceedingJoinPoint?
- JoinPoint: Context info about method (before/after)
- ProceedingJoinPoint: Used in
@Aroundadvice to proceed with method execution
@Around("execution(* com.example.service.*.*(..))")
public Object log(ProceedingJoinPoint jp) throws Throwable {
System.out.println("Before");
Object result = jp.proceed();
System.out.println("After");
return result;
}
40. What is weaving in AOP?
Process of linking aspects with application types at runtime (Spring AOP) or compile time (AspectJ).
41. What is Spring MVC?
Spring MVC is a web framework that separates application logic into:
- Model: Business logic
- View: UI layer (JSP, Thymeleaf, etc.)
- Controller: Handles HTTP requests and binds models to views
42. What are key annotations in Spring MVC?
@Controller@RestController@RequestMapping@GetMapping,@PostMapping, etc.@PathVariable,@RequestParam,@ModelAttribute@ResponseBody,@RequestBody
43. What is the difference between @Controller and @RestController?
| Annotation | Purpose |
|---|---|
@Controller | Returns views (HTML/JSP) |
@RestController | Returns data (JSON/XML), auto applies @ResponseBody |
44. How to handle HTTP GET and POST in Spring MVC?
@Controller
@RequestMapping("/users")
public class UserController {
@GetMapping("/{id}")
public String getUser(@PathVariable String id, Model model) {
model.addAttribute("user", service.findUser(id));
return "userDetails";
}
@PostMapping("/")
public String saveUser(@ModelAttribute User user) {
service.save(user);
return "redirect:/users";
}
}
45. What is @RequestParam vs @PathVariable?
@RequestParam: Query param@PathVariable: Part of URL path
@GetMapping("/search")
public String search(@RequestParam String keyword) {}
@GetMapping("/user/{id}")
public String getById(@PathVariable String id) {}
46. What is the use of @ModelAttribute?
- Binds request params to a model object
- Also can pre-populate model attributes
@PostMapping("/register")
public String register(@ModelAttribute User user) {
// fields auto-mapped from form
}
47. What is @RequestBody and @ResponseBody?
Used in REST APIs.
@RequestBody: Binds JSON to Java object.@ResponseBody: Converts Java object to JSON.
@PostMapping("/save")
@ResponseBody
public User save(@RequestBody User user) {
return userService.save(user);
}
48. How to validate form data in Spring MVC?
Use @Valid and BindingResult.
@PostMapping("/submit")
public String submit(@Valid @ModelAttribute User user, BindingResult result) {
if (result.hasErrors()) return "formPage";
return "success";
}
49. What is DispatcherServlet?
Front Controller in Spring MVC that:
- Receives all HTTP requests
- Delegates to controllers
- Resolves views
Defined in web.xml or Spring Boot auto-configured.
50. What is ViewResolver in Spring MVC?
Maps view names to actual view files (like JSPs or Thymeleaf templates).
@Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
51. What is HandlerMapping?
It maps requests to appropriate controller methods.
52. How to handle exceptions in Spring MVC?
- Use
@ControllerAdviceand@ExceptionHandler.
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(UserNotFoundException.class)
public String handleUserNotFound(Model model) {
model.addAttribute("error", "User not found");
return "errorPage";
}
}
53. How does Spring MVC support file upload?
Using MultipartFile.
@PostMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file) {
// save file logic
}
54. What is WebDataBinder?
Used to bind request parameters to model objects and register custom converters/validators.
55. What is @InitBinder?
Initializes WebDataBinder for a controller method.
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Date.class, new CustomDateEditor(...));
}
56. What is @SessionAttributes?
Stores model attributes in the HTTP session.
@SessionAttributes("user")
public class UserController {}
57. What is FlashAttribute?
Used to pass temporary attributes between redirects.
redirectAttributes.addFlashAttribute("message", "Saved successfully!");
58. How does Spring handle internationalization (i18n)?
Using ResourceBundleMessageSource and message.properties files.
@Bean
public MessageSource messageSource() {
ResourceBundleMessageSource source = new ResourceBundleMessageSource();
source.setBasename("messages");
return source;
}
59. What is form backing bean?
Java object that backs an HTML form, typically bound using @ModelAttribute.
60. What are common return types in Spring MVC controller methods?
String(view name)ModelAndViewResponseEntityvoid(for raw response)- Domain object (auto converted in REST)
Spring Boot Intreview
61. What is Spring Boot?
Spring Boot is an opinionated framework built on Spring that helps developers create stand-alone, production-ready applications quickly with minimal configuration.
62. What are the key features of Spring Boot?
- Auto-configuration
- Embedded servers (Tomcat, Jetty)
- Starter dependencies
- Spring Boot CLI
- Production-ready metrics via Actuator
63. What are Spring Boot Starters?
A set of convenient dependency descriptors to reduce manual configuration.
Examples:
spring-boot-starter-webspring-boot-starter-data-jpaspring-boot-starter-security
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
64. What is application.properties or application.yml?
Used for external configuration:
server.port=8081
spring.datasource.url=jdbc:mysql://localhost:3306/test
65. How to run a Spring Boot application?
mvn spring-boot:run
or
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
66. What is @SpringBootApplication?
It combines:
@Configuration@EnableAutoConfiguration@ComponentScan
67. What is Spring Boot Actuator?
Provides production-ready endpoints like:
/actuator/health/actuator/metrics/actuator/info
Enable in application.properties:
management.endpoints.web.exposure.include=*
68. What is the use of SpringApplication.run()?
It:
- Starts Spring context
- Triggers auto-configuration
- Starts embedded server
69. How to disable specific auto-configuration?
Use exclude in @SpringBootApplication:
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
70. What are some common Spring Boot annotations?
@SpringBootApplication@EnableAutoConfiguration@RestController@Value@Component,@Service,@Repository
Spring Security Intreview
71. What is Spring Security?
A powerful authentication and authorization framework for securing Spring-based applications.
72. What are the core features of Spring Security?
- Authentication
- Authorization
- Protection against CSRF, Session Fixation
- Password encoding
- Method-level security
73. How to secure a Spring Boot application with basic auth?
In application.properties:
spring.security.user.name=admin
spring.security.user.password=admin123
74. How to configure custom login in Spring Security?
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.authorizeRequests()
.anyRequest().authenticated();
}
75. What is the difference between Authentication and Authorization?
- Authentication: Verifying identity (e.g., username/password)
- Authorization: Verifying access rights (e.g., roles/permissions)
76. What is UserDetailsService?
An interface used to fetch user details for authentication.
@Service
public class MyUserDetailsService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) {
return new User("admin", "{noop}pass", List.of(new SimpleGrantedAuthority("ROLE_USER")));
}
}
77. What is CSRF and how to handle it?
CSRF (Cross-Site Request Forgery) is an attack where a user is tricked into submitting unwanted actions.
Spring enables CSRF protection by default.
To disable (not recommended):
http.csrf().disable();
78. What is the purpose of PasswordEncoder?
Used to hash passwords securely.
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
79. What are method-level security annotations?
@Secured("ROLE_ADMIN")@PreAuthorize("hasRole('ADMIN')")@PostAuthorize(...)
Enable with:
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
80. How to allow specific endpoints without authentication?
http.authorizeRequests()
.antMatchers("/public/**").permitAll()
.anyRequest().authenticated();
Spring Data JPA Interview
81. What is Spring Data JPA? Java Persistence API
A Spring project that simplifies JPA-based data access by reducing boilerplate code. It automatically implements repositories based on interfaces.
82. What is a Repository in Spring Data JPA?
A central interface for CRUD operations.
public interface UserRepository extends JpaRepository<User, Long> {
List<User> findByName(String name);
}
83. Difference between CrudRepository, JpaRepository, PagingAndSortingRepository?
| Interface | Features |
|---|---|
CrudRepository | Basic CRUD operations |
PagingAndSortingRepository | Adds pagination and sorting |
JpaRepository | Includes all above + batch operations |
CrudRepository -> PagingAndSortingRepository -> JpaRepository
84. What are derived query methods in Spring Data?
You can define queries based on method names.
List<User> findByEmail(String email);
List<User> findByAgeGreaterThan(int age);
85. How to write custom queries using @Query?
@Query("SELECT u FROM User u WHERE u.email = :email")
User getUserByEmail(@Param("email") String email);
86. What is @Modifying annotation?
Used with @Query for insert, update, delete operations.
@Modifying
@Query("DELETE FROM User u WHERE u.active = false")
void deleteInactiveUsers();
87. How to enable pagination in Spring Data?
Use Pageable and Page.
<User> findAll(Pageable pageable);
88. What is lazy vs eager loading in JPA?
- Lazy: Loads related data only when accessed.
- Eager: Loads all related data immediately.
@OneToMany(fetch = FetchType.LAZY) // or EAGER
private List<Order> orders;
89. How to handle transactions in Spring?
Use @Transactional on service methods.
@Transactional
public void updateUser(User user) {
// rollback if exception occurs
}
90. What is EntityManager and when is it used?
JPA interface for interacting with persistence context.
Used when more control is needed over queries and transactions.
@PersistenceContext
private EntityManager em;
Spring Testing
91. How to test Spring components?
Use Spring TestContext framework with JUnit 5 or TestNG.
@SpringBootTest
class MyServiceTest {
@Autowired MyService service;
}
92. What is @MockBean in Spring Boot tests?
Replaces a bean with a Mockito mock.
@MockBean
private UserRepository userRepo;
93. What is @DataJpaTest?
Used to test only JPA components.
@DataJpaTest
class RepoTest {
@Autowired UserRepository repo;
}
94. What is @WebMvcTest?
Used to test only Spring MVC components like controllers.
Spring AOP
95. What is Spring AOP?
Aspect-Oriented Programming — separates cross-cutting concerns like logging, security.
Common annotations:
@Aspect@Before,@After,@Around
@Aspect
@Component
public class LoggingAspect {
@Before("execution(* com.example.service.*.*(..))")
public void logBefore(JoinPoint jp) {
System.out.println("Method called: " + jp.getSignature());
}
}
96. What are Pointcut and Advice?
- Pointcut: Expression to match join points (methods)
- Advice: Code executed at matched point (before, after, etc.)
Spring Cloud & Microservices
97. What is Spring Cloud?
Set of tools for building microservices:
- Service Discovery (Eureka)
- Load Balancing (Ribbon)
- Config Server
- Circuit Breaker (Resilience4j, Hystrix)
- API Gateway (Zuul, Spring Cloud Gateway)
98. What is Spring Cloud Config Server?
Centralized configuration for all microservices.
99. What is Eureka Server?
Service Registry used for service discovery.
@EnableEurekaServer
@SpringBootApplication
public class EurekaApp {}
Clients register with:
@EnableEurekaClient
100. What are some best practices in Spring development?
- Use constructor injection
- Avoid field injection
- Use
@Transactionalon service layer - Follow layered architecture
- Use profiles for environment configuration
- Use
@ComponentScanwisely to avoid loading unnecessary beans
