Java Notes
35+ Spring Framework and Spring Boot interview questions covering IoC, DI, annotations, REST, JPA, Security, and microservices concepts.
1. What is Spring Framework? Why use it?
Spring is a comprehensive Java framework providing IoC container, DI, AOP, and modules for data access, web, security, etc. Benefits: loose coupling, testability, productivity, enterprise-ready features.
3. What is Dependency Injection? Types?
DI is the mechanism of IoC. Container injects dependencies into beans:
- Constructor Injection (recommended): Immutable, testable
- Setter Injection: Optional dependencies
- Field Injection (avoid): Requires reflection, hard to test
4. What are Spring Bean Scopes?
| Scope | Instance Count | Lifecycle |
|---|---|---|
| singleton (default) | One per container | Container lifecycle |
| prototype | New per request | Not managed after creation |
| request | One per HTTP request | Request lifetime |
| session | One per HTTP session | Session lifetime |
| application | One per ServletContext | App lifetime |
5. What is @SpringBootApplication?
Combines three annotations:
@Configuration: Defines bean configurations@EnableAutoConfiguration: Auto-configures based on classpath@ComponentScan: Scans for components in current + sub packages
6. What is auto-configuration in Spring Boot?
Spring Boot examines classpath JARs and automatically configures beans. Example: If spring-boot-starter-web is present → auto-configures embedded Tomcat, DispatcherServlet, Jackson.
Controlled by @Conditional annotations. Override with your own @Bean definitions.
7. @Component vs @Service vs @Repository vs @Controller?
All are @Component specializations:
@Component: Generic bean@Service: Business logic (semantic only)@Repository: DAO + automatic exception translation@Controller: Web MVC controller@RestController:@Controller+@ResponseBody
8. What is @Autowired? How does it resolve dependencies?
Spring's DI annotation. Resolution order:
- By type
- By
@Qualifiername - By
@Primary - By field name matching bean name
9. @RequestMapping vs @GetMapping vs @PostMapping?
@RequestMapping(value="/users", method=RequestMethod.GET) // Verbose
@GetMapping("/users") // Shortcut for GET
@PostMapping("/users") // Shortcut for POST
@PutMapping("/users/{id}")
@DeleteMapping("/users/{id}")
@PatchMapping("/users/{id}")10. What is @Transactional?
Manages database transactions declaratively:
@Transactional
public void transferMoney(Long from, Long to, double amount) {
debit(from, amount); // If this succeeds but below fails...
credit(to, amount); // ...both are rolled back
}Properties: propagation, isolation, timeout, readOnly, rollbackFor.
11. What is Spring AOP?
Aspect-Oriented Programming — separates cross-cutting concerns:
- Aspect: Module containing cross-cutting logic
- Advice: Action (Before, After, Around, AfterReturning, AfterThrowing)
- Pointcut: Expression defining where advice applies
- JoinPoint: Point in execution where advice runs
@Aspect @Component
public class LoggingAspect {
@Around("execution(* com.example.service.*.*(..))")
public Object logExecution(ProceedingJoinPoint jp) throws Throwable {
long start = System.currentTimeMillis();
Object result = jp.proceed();
long elapsed = System.currentTimeMillis() - start;
log.info("{}.{} took {}ms", jp.getTarget().getClass().getSimpleName(),
jp.getSignature().getName(), elapsed);
return result;
}
}12. What is Spring Security? How does authentication work?
Spring Security provides:
- Authentication: Who are you? (login)
- Authorization: What can you do? (roles/permissions)
Flow: Request → Security Filter Chain → AuthenticationManager → AuthenticationProvider → UserDetailsService → PasswordEncoder
13. What is JWT? How is it used with Spring Security?
JSON Web Token for stateless authentication:
- User logs in → server generates JWT (Header.Payload.Signature)
- Client sends JWT in
Authorization: Bearer <token>header - JwtFilter extracts → validates → sets SecurityContext
- Controller accesses authenticated user
14. @RestControllerAdvice — what is it?
Global exception handler for all REST controllers:
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<?> handleNotFound(ResourceNotFoundException ex) {
return ResponseEntity.status(404).body(Map.of("error", ex.getMessage()));
}
}15. What is Spring Data JPA?
Abstraction over JPA/Hibernate that eliminates boilerplate:
- Define interface extending
JpaRepository - Spring auto-generates implementation
- Method names become queries:
findByNameAndAge(String name, int age)
16-35. Additional Questions
16. What is Spring Boot Actuator? Production monitoring endpoints: /health, /metrics, /info, /env, /loggers.
17. What are Spring Boot profiles? Environment-specific configuration. spring.profiles.active=dev loads application-dev.properties.
18. What is @Value annotation? Injects values from properties: @Value("${app.name}") private String appName;
19. What is @ConfigurationProperties? Type-safe configuration binding to POJO classes.
20. Explain Spring MVC request flow? DispatcherServlet → HandlerMapping → Controller → ViewResolver → View.
21. What is ResponseEntity? Represents entire HTTP response (status code, headers, body).
22. What is @PathVariable vs @RequestParam? PathVariable: /users/{id}. RequestParam: /users?page=1&size=10.
23. What is Spring Boot DevTools? Auto-restart on code change, LiveReload, relaxed property binding for development.
24. How does Spring Boot auto-configuration work internally? Reads META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports, evaluates @Conditional annotations.
25. What is @Conditional annotation? Registers bean only when condition is met (OnProperty, OnClass, OnBean, OnMissingBean).
26. What is Spring Cloud? Key components? Microservices toolkit: Eureka (discovery), Gateway (routing), Config (centralized config), Circuit Breaker.
27. What is Circuit Breaker pattern? Prevents cascading failures. States: CLOSED → OPEN (after failures) → HALF_OPEN (probe).
28. Difference between monolith and microservices? Monolith: single deployable unit. Microservices: independent services, own DB, communicate via HTTP/messaging.
29. What is @EnableCaching? Enables Spring's caching abstraction. Use @Cacheable, @CacheEvict, @CachePut.
30. What is Spring WebFlux? Reactive, non-blocking web framework. Uses Reactor (Mono, Flux). For high-concurrency, non-blocking I/O.
31. What is the difference between @Bean and @Component? @Bean: method-level, in @Configuration class. @Component: class-level, auto-scanned.
32. What is ApplicationContext vs BeanFactory? ApplicationContext: eager init, events, i18n, AOP. BeanFactory: lazy init, basic.
33. What is Spring Boot Starter? Curated dependency groups. spring-boot-starter-web includes Tomcat, Jackson, Spring MVC.
34. What is @Async in Spring? Executes method in a separate thread. Requires @EnableAsync.
35. How to handle file upload in Spring Boot? Use @RequestParam MultipartFile file. Configure spring.servlet.multipart.max-file-size.
16. How does Spring Boot Auto-Configuration work?
Answer: @EnableAutoConfiguration automatically configures beans by looking at available dependencies on the classpath. Conditional annotations (@ConditionalOnClass, @ConditionalOnProperty) decide what to configure. Auto-configuration classes are listed in the spring.factories file.
17. @Component vs @Service vs @Repository vs @Controller?
Answer: All are specializations of @Component:
@Component— generic bean@Service— business logic layer@Repository— data access layer (+ SQL exception translation)@Controller— web layer (MVC controller)
They are functionally the same but provide semantic clarity and enable specific features.
18. Explain the Spring Bean Lifecycle.
Answer: Instantiation → Populate Properties → BeanNameAware → BeanFactoryAware → ApplicationContextAware → @PostConstruct → InitializingBean.afterPropertiesSet() → Custom init-method → Ready → @PreDestroy → DisposableBean.destroy() → Custom destroy-method.
19. When to use @Qualifier annotation?
Answer: When there are multiple beans of the same type and @Autowired causes ambiguity. @Qualifier injects by a specific bean name.
@Autowired
@Qualifier("mysqlDataSource")
private DataSource dataSource;20. What are Spring Profiles?
Answer: Environment-specific configuration (dev, test, prod). You can make beans profile-specific using @Profile("dev"). Set active profile: spring.profiles.active=dev. Different properties files: application-dev.yml, application-prod.yml.
21. What is Spring AOP (Aspect Oriented Programming)?
Answer: Separating cross-cutting concerns (logging, security, transaction). Key terms: Aspect, Advice (Before, After, Around), Pointcut (where to apply), JoinPoint (method execution point). Define @Aspect classes.
22. How does @Transactional annotation work?
Answer: Proxy-based — Spring creates a proxy around the bean that handles transaction start/commit/rollback. Default: rollback on RuntimeException. propagation, isolation, timeout, rollbackFor attributes are available.
23. What is Spring Boot Actuator?
Answer: Provides production-ready features — health checks, metrics, info, environment details, thread dump. /actuator/health, /actuator/metrics endpoints are exposed. You can also create custom health indicators.
24. @RequestMapping vs @GetMapping/@PostMapping?
Answer: @RequestMapping is generic (any HTTP method). @GetMapping, @PostMapping, etc. are shortcuts for specific HTTP methods. In modern code, specific annotations are preferred for readability.
25. Spring Boot Exception Handling - @ControllerAdvice?
Answer: Global exception handler — handles exceptions from all controllers in one place. Define @ExceptionHandler methods that handle specific exception types. Provides consistent error response across the entire application.
26. How to write Custom Queries in Spring Data JPA?
Answer: Three ways: (1) Method name conventions (findByNameAndAge), (2) @Query annotation with JPQL, (3) Native SQL queries with nativeQuery=true. Pagination/Sorting: pass the Pageable parameter.
27. What is Circular Dependency? How to solve it?
Answer: Bean A depends on B, B depends on A. Solutions: @Lazy annotation, setter injection instead of constructor injection, redesign (extract common logic to third bean), @PostConstruct initialization.
28. Spring Boot application.properties vs application.yml?
Answer: Both serve the same purpose. YAML represents hierarchical structure better and profiles support is easier. Properties uses a flat key=value format. YAML is indentation-sensitive. Both can be used simultaneously.
29. What is a Spring Boot Starter?
Answer: Pre-configured dependency bundles. spring-boot-starter-web includes Spring MVC, embedded Tomcat, Jackson, and more. With starters, there is no need for manual dependency management. Common starters: web, data-jpa, security, test, actuator.
30. @Value vs @ConfigurationProperties?
Answer: @Value("${property}") injects a single value. @ConfigurationProperties(prefix="app") binds an entire group of properties to a type-safe POJO. @ConfigurationProperties is preferred for complex configuration — validation, IDE support, documentation.
Summary
In this chapter, we learned about Spring Framework Interview Questions in detail. Here are the key points:
- Basic introduction to the concept and why it is needed
- Syntax and structure with complete examples
- Internal working and best practices
- Real-world applications and use cases
- Common mistakes and how to avoid them
- How this topic is asked in interviews
To practice these concepts, write and run the code in your IDE and verify the output. Modify each example and experiment so that you deeply understand the concept.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Spring Framework Interview Questions.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, interview, questions, spring
Related Java Master Course Topics