issue 117apr 27mmxxvi
est. 2017
Sun, 27 Apr 2026
vol. IX · no. 117
PapersAdda
placement intelligence, since 2017
640+ briefs · 24 campuses · by reservation
verified offers · sourced from r/developersIndia
razorpay₹65.00 LPA· iit-d · sde-1google₹54.00 LPA· iiit-h · swe-imicrosoft₹49.50 LPA· iit-b · sdeatlassian₹38.00 LPA· nit-w · sde-1amazon₹44.20 LPA· bits-p · sde-1uber₹42.00 LPA· iit-kgp · sde-1razorpay₹65.00 LPA· iit-d · sde-1google₹54.00 LPA· iiit-h · swe-imicrosoft₹49.50 LPA· iit-b · sdeatlassian₹38.00 LPA· nit-w · sde-1amazon₹44.20 LPA· bits-p · sde-1uber₹42.00 LPA· iit-kgp · sde-1

Top 50 Spring Framework Interview Questions 2026

20 min read
Interview Questions
Updated: 8 Jun 2026
Aditya Sharma
Aditya's Edit

PapersAdda 2026 Placement Cycle

By Aditya Sharma·Founder & Editor, PapersAdda

What changed in 2026 drives

Mass-recruiter offer letters are flatter for 2026 batch - the 4-5 LPA ASE band has barely budged in three years while inflation eats real wages. Premium tracks (Digital, Pro, Elite, Specialist) are still where the differential lives, and they are entirely test-driven. If you are aiming higher than the default offer, the coding round is not optional pageantry - it is the entire interview.

What I'd actually study for this

  • 01Two solid coding-round answers (1 medium-hard DSA each, with edge-case discussion) > five half-baked ones
  • 02One real project you can defend end-to-end - file paths, design decisions, and what you would change
  • 03One DBMS schema you actually built (not a textbook ER diagram), with at least 3 join-heavy queries written from memory
  • 04Three behavioural STAR stories: failure recovered, conflict handled, ownership taken

Where most candidates trip up

The single biggest mistake is treating company-specific guides as primary prep and DSA as secondary. It is the opposite. Mass recruiters use the test as a filter, but premium tracks at every IT services company use coding to allocate offer band. Spend 70% of prep time on DSA + system fundamentals, 20% on company-specific patterns, 10% on HR rehearsal. Reverse that ratio and you collect the default offer.

Editorial commentary by Aditya Sharma · written for PapersAdda · not generated, not aggregated.

Last Updated: June 2026 | Level: Freshers to 3 Years Experience | Read Time: ~22 min

Spring Framework is the backbone of Java enterprise development. Candidates report that IoC/DI, bean lifecycle, AOP, transaction management, and Spring MVC are the most frequently tested topics in Java backend interviews. This guide covers 50 questions from core container concepts to Spring MVC and Spring Data.

Pair with Java Interview Questions 2026 and Hibernate Interview Questions 2026 for complete Java backend preparation. Confirm current interview requirements on the official careers portal of your target company.


Table of Contents

  1. Core Spring: IoC and DI (Q1-Q15)
  2. Bean Lifecycle and Scopes (Q16-Q22)
  3. Aspect-Oriented Programming (Q23-Q29)
  4. Spring MVC (Q30-Q38)
  5. Spring Data and Transactions (Q39-Q46)
  6. Spring Security Basics (Q47-Q50)
  7. Mock Interview: 5 Questions
  8. FAQ

Core Spring: IoC and DI

Q1. What is the Spring Framework? Easy

  • IoC (Inversion of Control) container
  • Dependency Injection (DI)
  • Aspect-Oriented Programming (AOP)
  • Data access abstraction (JDBC, ORM integration)
  • MVC web framework
  • Transaction management
  • Security (Spring Security)

Spring's core principle is that the framework manages object creation and wiring, so application code only describes dependencies, not how to satisfy them.


Q2. What is Inversion of Control (IoC)? Easy

Without IoC:

// Application controls object creation
UserService service = new UserService(new JdbcUserRepository(new DataSource(...)));

With IoC:

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;
    // Spring creates UserService and injects UserRepository
}

The "inversion" is that the application no longer controls object lifecycle, the container does.


Q3. What is Dependency Injection? Easy

Three types of DI:

// 1. Constructor Injection (recommended)
@Service
public class OrderService {
    private final UserRepository userRepository;
    private final PaymentService paymentService;
    
    public OrderService(UserRepository ur, PaymentService ps) {
        this.userRepository = ur;
        this.paymentService = ps;
    }
}

// 2. Setter Injection (for optional dependencies)
@Service
public class NotificationService {
    private EmailSender emailSender;
    
    @Autowired(required = false)
    public void setEmailSender(EmailSender sender) {
        this.emailSender = sender;
    }
}

// 3. Field Injection (convenient but not recommended for testing)
@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;
}

Q4. What is the Spring IoC container? Easy

  • BeanFactory: basic container (lazy initialization by default)
  • ApplicationContext: enterprise-grade superset (eager init, AOP, events, i18n)
// BeanFactory
BeanFactory factory = new XmlBeanFactory(new FileSystemResource("beans.xml"));

// ApplicationContext (use this in production)
ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
// or
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");

UserService service = ctx.getBean(UserService.class);

Q5. What is a Spring Bean? Easy

// Stereotype annotations create beans
@Component       // generic component
@Service         // service layer
@Repository      // data access layer (also adds exception translation)
@Controller      // Spring MVC controller
@RestController  // @Controller + @ResponseBody

// @Bean: explicit bean in @Configuration class
@Configuration
public class AppConfig {
    @Bean
    public DataSource dataSource() {
        HikariDataSource ds = new HikariDataSource();
        ds.setJdbcUrl("jdbc:postgresql://localhost:5432/mydb");
        return ds;
    }
}

Q6. What is @Autowired? Easy

@Service
public class UserService {
    private final UserRepository repository;
    
    // Spring 4.3+: single-constructor @Autowired is optional
    public UserService(UserRepository repository) {
        this.repository = repository;
    }
}

// @Qualifier: resolve ambiguity when multiple beans of same type
@Autowired
@Qualifier("postgresRepository")
private UserRepository userRepository;

// @Primary: mark preferred bean when multiple match
@Bean
@Primary
public UserRepository defaultRepository() {
    return new PostgresUserRepository();
}

Q7. What is the difference between @Component, @Service, @Repository, and @Controller? Easy

All four are specializations of @Component (all create beans). The differences are semantic and functional:

AnnotationLayerExtra behavior
@ComponentGenericNone
@ServiceServiceNone (semantic only)
@RepositoryDAOSpring translates SQL/JPA exceptions to DataAccessException
@ControllerMVC ControllerHandles HTTP requests via @RequestMapping
@RestControllerREST Controller@Controller + @ResponseBody on every method

Q8. What is @Configuration and @Bean? Medium

@Configuration
public class DatabaseConfig {
    @Value("${db.url}")
    private String dbUrl;
    
    @Bean
    public DataSource dataSource() {
        HikariDataSource ds = new HikariDataSource();
        ds.setJdbcUrl(dbUrl);
        return ds;
    }
    
    @Bean
    @Scope("prototype")
    public Connection getConnection() throws SQLException {
        return dataSource().getConnection();
    }
    
    // @Bean methods in @Configuration use CGLIB proxy:
    // multiple calls to dataSource() return the SAME bean
}

Q9. What is @Value and @PropertySource? Medium

@Configuration
@PropertySource("classpath:application.properties")
public class AppConfig {
    @Value("${server.port:8080}")
    private int serverPort;  // default 8080 if not set
    
    @Value("${app.feature.enabled:false}")
    private boolean featureEnabled;
    
    @Value("${allowed.origins}")
    private String[] allowedOrigins;
    
    // Spring Expression Language
    @Value("#{systemProperties['user.home']}")
    private String userHome;
}

Q10. What is component scanning? Medium

@Configuration
@ComponentScan(basePackages = "com.example")
public class AppConfig {
    // Spring scans com.example.** for @Component, @Service, etc.
}

// Or filter:
@ComponentScan(
    basePackages = "com.example",
    excludeFilters = @ComponentScan.Filter(
        type = FilterType.ANNOTATION,
        classes = Repository.class
    )
)

Q11. What is @Import and @ImportResource? Medium

@Configuration
@Import({DatabaseConfig.class, SecurityConfig.class})
public class AppConfig { }

// Import XML configuration into Java config
@Configuration
@ImportResource("classpath:legacy-beans.xml")
public class AppConfig { }

Q12. What is Environment and @Profile? Medium

// Profile-specific beans
@Bean
@Profile("dev")
public DataSource devDataSource() {
    return new H2DataSource();
}

@Bean
@Profile("prod")
public DataSource prodDataSource() {
    return new PostgresDataSource();
}

// Activate via property
// -Dspring.profiles.active=prod
// or in application.properties:
// spring.profiles.active=prod

// In code
@Autowired
Environment env;
env.getActiveProfiles();
env.getProperty("db.url");

Q13. What is the ApplicationContext refresh lifecycle? Advanced

  1. Load bean definitions (scan/XML/Java config)
  2. Pre-instantiate singletons (eager init)
  3. Call @PostConstruct methods
  4. Publish ContextRefreshedEvent

When closed:

  1. Call @PreDestroy methods
  2. Destroy singleton beans
  3. Publish ContextClosedEvent
@Component
class InitDemo {
    @PostConstruct
    void init() { System.out.println("Bean initialized"); }
    
    @PreDestroy
    void cleanup() { System.out.println("Bean destroyed"); }
}

Q14. What is @Lazy? Medium

// By default, singletons are created at context startup
// @Lazy defers creation to first use
@Component
@Lazy
public class HeavyService {
    public HeavyService() {
        System.out.println("Created only on first use");
    }
}

// @Lazy on @Autowired injection point (even if bean is eager)
@Autowired
@Lazy
private HeavyService service;

Q15. Predict the output: Medium

@Component
class A {
    @Autowired B b;
    @PostConstruct void init() { System.out.println("A initialized"); }
}

@Component
class B {
    @PostConstruct void init() { System.out.println("B initialized"); }
}

Output:

B initialized
A initialized

Explanation: Spring creates B first (it has no dependencies), then creates A and injects B. @PostConstruct runs after injection. B is initialized before A.


Bean Lifecycle and Scopes

Q16. What are Spring bean scopes? Medium

ScopeDescriptionThread-safe
singletonOne instance per container (default)No (shared state)
prototypeNew instance per getBean()Yes (each request gets own)
requestOne per HTTP requestYes
sessionOne per HTTP sessionYes
applicationOne per ServletContextNo
websocketOne per WebSocket sessionYes
@Bean
@Scope("prototype")
public DatabaseConnection getConnection() {
    return new DatabaseConnection();
}

// Or via annotation
@Component
@Scope("request")
public class RequestContext { }

Q17. What happens when a prototype bean is injected into a singleton? Advanced

@Component
@Scope("prototype")
public class PrototypeBean { }

@Service
public class SingletonService {
    @Autowired
    private PrototypeBean proto;  // PROBLEM: injected ONCE at creation
    // proto is always the same instance, defeating prototype
}

// Fix 1: ApplicationContext.getBean()
@Autowired ApplicationContext ctx;
public void method() {
    PrototypeBean newProto = ctx.getBean(PrototypeBean.class);
}

// Fix 2: @Scope with proxyMode
@Component
@Scope(value = "prototype", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class PrototypeBean { }

Q18. What is the bean lifecycle in detail? Advanced

1. Instantiate (constructor)
2. Inject dependencies (@Autowired)
3. Set bean name (BeanNameAware.setBeanName)
4. Set application context (ApplicationContextAware.setApplicationContext)
5. BeanPostProcessor.postProcessBeforeInitialization
6. @PostConstruct / InitializingBean.afterPropertiesSet / init-method
7. BeanPostProcessor.postProcessAfterInitialization
--- bean ready for use ---
8. @PreDestroy / DisposableBean.destroy / destroy-method

Q19. What is BeanPostProcessor? Advanced

@Component
public class LoggingBeanPostProcessor implements BeanPostProcessor {
    
    @Override
    public Object postProcessBeforeInitialization(Object bean, String name) {
        System.out.println("Before init: " + name);
        return bean;
    }
    
    @Override
    public Object postProcessAfterInitialization(Object bean, String name) {
        System.out.println("After init: " + name);
        // Can return a proxy wrapping bean
        return bean;
    }
}

Spring itself uses BeanPostProcessor for @Autowired, @Transactional, AOP, and @Async.


Q20. What is FactoryBean? Advanced

public class CustomConnectionFactoryBean implements FactoryBean<Connection> {
    @Override
    public Connection getObject() throws Exception {
        return DriverManager.getConnection(url, user, password);
    }
    
    @Override
    public Class<?> getObjectType() { return Connection.class; }
    
    @Override
    public boolean isSingleton() { return false; }
}

FactoryBean lets you customize bean creation logic. Access the factory itself with &beanName, access the product with beanName.


Q21. What is @DependsOn? Easy

@Component
@DependsOn({"databaseInitializer", "cacheWarmer"})
public class UserService {
    // Spring guarantees databaseInitializer and cacheWarmer
    // are fully initialized before UserService
}

Q22. Predict the output: scope + lifecycle. Medium

@Component
class Counter {
    private int count = 0;
    public int increment() { return ++count; }
}

// In a controller
@Autowired Counter counter;

// Three requests call:
counter.increment(); // first request
counter.increment(); // second request
counter.increment(); // third request

Output: 1, then 2, then 3

Explanation: Counter is singleton-scoped by default. All three requests use the same instance, so state accumulates. If Counter were @Scope("prototype"), each injection would get a fresh instance starting at 0.


Aspect-Oriented Programming

Q23. What is AOP? Medium

Key concepts:

  • Aspect: The cross-cutting concern (e.g., logging)
  • Join Point: A point in program execution (method call, exception throw)
  • Pointcut: Expression matching join points ("all methods in com.example.service.*")
  • Advice: Code run at matched join points (before/after/around)
  • Weaving: The process of applying aspects to target objects
@Aspect
@Component
public class LoggingAspect {
    @Around("execution(* com.example.service.*.*(..))")
    public Object logMethod(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("Before: " + pjp.getSignature());
        Object result = pjp.proceed();
        System.out.println("After: " + pjp.getSignature());
        return result;
    }
}

Q24. What are the types of advice in Spring AOP? Medium

Advice typeWhenAnnotation
BeforeBefore method executes@Before
After ReturningAfter successful return@AfterReturning
After ThrowingWhen exception thrown@AfterThrowing
After (finally)After method, regardless@After
AroundWraps entire method@Around
@Before("execution(* com.example.service.UserService.*(..))") 
public void logBefore(JoinPoint jp) {
    System.out.println("Calling: " + jp.getSignature().getName());
}

@AfterReturning(pointcut = "execution(* findUser(..))", returning = "user")
public void logReturn(Object user) {
    System.out.println("Returned: " + user);
}

@AfterThrowing(pointcut = "execution(* *.*(..)) ", throwing = "ex")
public void logException(Exception ex) {
    System.out.println("Exception: " + ex.getMessage());
}

Q25. What are pointcut expressions? Advanced

// execution: matches method execution join points (most common)
@Pointcut("execution(public * com.example.service.*.*(..))")
void publicServiceMethods() {}

// within: all methods in a package
@Pointcut("within(com.example.repository.*)")
void repositoryLayer() {}

// @annotation: methods annotated with a specific annotation
@Pointcut("@annotation(com.example.Cacheable)")
void cacheableMethods() {}

// args: matches by argument type
@Pointcut("args(java.io.Serializable)")
void methodsWithSerializableArgs() {}

// Combine with &&, ||, !
@Before("publicServiceMethods() && !repositoryLayer()")
void advice(JoinPoint jp) { }

Q26. How does Spring AOP implement proxying? Advanced

  1. JDK Dynamic Proxy: for beans implementing interfaces. Spring creates a proxy implementing the same interface.
  2. CGLIB Proxy: for concrete classes (no interface). Spring subclasses the target class.
// Force CGLIB for everything:
@EnableAspectJAutoProxy(proxyTargetClass = true)

// Impact: if a bean has no interface, CGLIB is used automatically.
// If you inject the bean's class (not interface), you need CGLIB.

// Check if a bean is proxied
System.out.println(userService.getClass().getName());
// com.example.service.UserService$$EnhancerBySpringCGLIB$$...

Q27. What is @Transactional as an AOP example? Medium

@Service
public class OrderService {
    @Transactional
    public void placeOrder(Order order) {
        userRepo.save(order.getUser());
        inventoryRepo.deduct(order.getItems());
        paymentRepo.charge(order.getPayment());
        // If ANY line throws, ALL are rolled back
    }
}
// @Transactional is implemented via Spring AOP:
// an Around advice wraps the method in a transaction proxy

Q28. What is the self-invocation problem in AOP? Advanced

@Service
public class UserService {
    @Transactional
    public void createUser(User user) {
        userRepo.save(user);
        sendWelcomeEmail(user);  // PROBLEM: self-invocation bypasses proxy
    }
    
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void sendWelcomeEmail(User user) {
        // This @Transactional is IGNORED when called from createUser()
        // because it goes through this.sendWelcomeEmail(), not the proxy
    }
}
// Fix: inject self, call via interface, or use AspectJ compile-time weaving

Q29. What is AspectJ vs Spring AOP? Advanced

FeatureSpring AOPAspectJ
Join pointsMethod execution onlyAny (field access, constructor, etc.)
WeavingRuntime (proxy)Compile-time or load-time
PerformanceSmall proxy overheadZero runtime overhead
ScopeSpring beans onlyAny Java class
Self-invocationNot supportedSupported

Spring AOP is sufficient for most applications. Use AspectJ for non-bean classes or non-method join points.


Spring MVC

Q30. What is Spring MVC? Easy

Request -> DispatcherServlet -> HandlerMapping -> Controller
Controller -> ModelAndView -> ViewResolver -> Response

Q31. What is DispatcherServlet? Medium

  1. Receives all HTTP requests
  2. Consults HandlerMapping to find the correct controller method
  3. Invokes the method (via HandlerAdapter)
  4. Resolves the view
  5. Renders the response

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

In Spring Boot, DispatcherServlet is auto-configured.


Q32. What are request mapping annotations? Medium

@RestController
@RequestMapping("/api/users")
public class UserController {
    
    @GetMapping                          // GET /api/users
    public List<User> list() { ... }
    
    @GetMapping("/{id}")                 // GET /api/users/42
    public User getById(@PathVariable Long id) { ... }
    
    @PostMapping                         // POST /api/users
    public User create(@RequestBody User user) { ... }
    
    @PutMapping("/{id}")                 // PUT /api/users/42
    public User update(@PathVariable Long id, @RequestBody User user) { ... }
    
    @DeleteMapping("/{id}")              // DELETE /api/users/42
    public void delete(@PathVariable Long id) { ... }
    
    @GetMapping("/search")
    public List<User> search(
        @RequestParam String name,
        @RequestParam(required=false, defaultValue="10") int limit
    ) { ... }
}

Q33. What are @RequestBody and @ResponseBody? Easy

// @RequestBody: deserialize HTTP request body into Java object (via Jackson/Gson)
@PostMapping("/users")
public ResponseEntity<User> create(@RequestBody @Valid User user) {
    User saved = userService.save(user);
    return ResponseEntity.status(HttpStatus.CREATED).body(saved);
}

// @ResponseBody: serialize return value into HTTP response body
@GetMapping("/users/{id}")
@ResponseBody
public User getUser(@PathVariable Long id) {
    return userService.findById(id);
}

// @RestController = @Controller + @ResponseBody on every method

Q34. What is ResponseEntity? Medium

// ResponseEntity: full control over HTTP response
@GetMapping("/users/{id}")
public ResponseEntity<User> getUser(@PathVariable Long id) {
    return userService.findById(id)
        .map(user -> ResponseEntity.ok(user))
        .orElse(ResponseEntity.notFound().build());
}

// With headers
return ResponseEntity
    .status(HttpStatus.CREATED)
    .header("Location", "/api/users/" + saved.getId())
    .header("X-Custom", "value")
    .body(saved);

Q35. What is @ExceptionHandler and @ControllerAdvice? Medium

// @ControllerAdvice: global exception handling
@ControllerAdvice
public class GlobalExceptionHandler {
    
    @ExceptionHandler(UserNotFoundException.class)
    public ResponseEntity<ErrorResponse> handleNotFound(UserNotFoundException ex) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND)
            .body(new ErrorResponse("USER_NOT_FOUND", ex.getMessage()));
    }
    
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<ErrorResponse> handleValidation(MethodArgumentNotValidException ex) {
        List<String> errors = ex.getBindingResult().getFieldErrors()
            .stream().map(FieldError::getDefaultMessage).collect(Collectors.toList());
        return ResponseEntity.badRequest().body(new ErrorResponse("VALIDATION_FAILED", errors));
    }
}

Q36. What is @Valid and @Validated? Medium

public class CreateUserRequest {
    @NotBlank(message = "Name is required")
    @Size(min = 2, max = 50)
    private String name;
    
    @Email(message = "Valid email required")
    @NotBlank
    private String email;
    
    @Min(18) @Max(120)
    private int age;
}

@PostMapping("/users")
public ResponseEntity<User> create(@RequestBody @Valid CreateUserRequest request,
                                   BindingResult result) {
    if (result.hasErrors()) {
        throw new ValidationException(result);
    }
    return ResponseEntity.ok(userService.create(request));
}

Q37. What is Spring MVC Interceptors? Advanced

@Component
public class AuthInterceptor implements HandlerInterceptor {
    
    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) {
        String token = req.getHeader("Authorization");
        if (!tokenService.isValid(token)) {
            res.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;  // abort request
        }
        return true;  // continue
    }
    
    @Override
    public void postHandle(HttpServletRequest req, HttpServletResponse res,
                           Object handler, ModelAndView mav) {
        // After controller, before view
    }
    
    @Override
    public void afterCompletion(HttpServletRequest req, HttpServletResponse res,
                                Object handler, Exception ex) {
        // After view rendered
    }
}

Q38. What is content negotiation? Medium

// Spring MVC can return different formats based on Accept header or URL suffix
@GetMapping(value = "/users/{id}",
    produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
public User getUser(@PathVariable Long id) {
    return userService.findById(id);
}

// Accept: application/json -> JSON response
// Accept: application/xml  -> XML response (needs jackson-dataformat-xml)

Spring Data and Transactions

Q39. What is Spring Data JPA? Medium

// Repository interface - no implementation needed!
public interface UserRepository extends JpaRepository<User, Long> {
    
    // Query from method name
    List<User> findByActiveTrue();
    Optional<User> findByEmail(String email);
    List<User> findByAgeGreaterThan(int age);
    Page<User> findByDepartment(String dept, Pageable pageable);
    
    // JPQL query
    @Query("SELECT u FROM User u WHERE u.name LIKE :pattern")
    List<User> searchByName(@Param("pattern") String pattern);
    
    // Native SQL
    @Query(value = "SELECT * FROM users WHERE dept = :dept LIMIT :limit",
           nativeQuery = true)
    List<User> findByDept(@Param("dept") String dept, @Param("limit") int limit);
}

Q40. What is transaction propagation? Advanced

// Propagation.REQUIRED (default): join existing or create new
@Transactional(propagation = Propagation.REQUIRED)
void methodA() { methodB(); }

@Transactional(propagation = Propagation.REQUIRED)
void methodB() { /* runs in methodA's transaction */ }

// Propagation.REQUIRES_NEW: always creates new transaction
@Transactional(propagation = Propagation.REQUIRES_NEW)
void auditLog(String event) { /* always in own transaction */ }

// Propagation.NEVER: throw if in a transaction
// Propagation.MANDATORY: throw if NOT in a transaction
// Propagation.NOT_SUPPORTED: suspend existing transaction
// Propagation.SUPPORTS: use existing or run without
// Propagation.NESTED: nested transaction (savepoint)

Q41. What is transaction isolation? Advanced

@Transactional(isolation = Isolation.READ_COMMITTED)
public User findUser(Long id) { ... }
Isolation LevelDirty ReadNon-Repeatable ReadPhantom Read
READ_UNCOMMITTEDPossiblePossiblePossible
READ_COMMITTEDPreventedPossiblePossible
REPEATABLE_READPreventedPreventedPossible
SERIALIZABLEPreventedPreventedPrevented

Q42. What is @Transactional rollback behavior? Medium

// Default: rollback on RuntimeException and Error
// Does NOT rollback on checked exceptions by default

@Transactional(rollbackFor = Exception.class)  // rollback on checked too
void methodA() throws IOException { }

@Transactional(noRollbackFor = ValidationException.class)
void methodB() { }  // won't rollback on ValidationException

// Programmatic rollback
@Autowired
TransactionStatus status;
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

Q43. What is Spring Data pagination? Medium

// Service
Page<User> page = userRepository.findAll(
    PageRequest.of(0, 10, Sort.by("name").ascending())
);

page.getContent();         // List<User> for current page
page.getTotalElements();   // total count
page.getTotalPages();      // total pages
page.getNumber();          // current page number (0-indexed)
page.hasNext();            // whether next page exists

// REST endpoint
@GetMapping("/users")
public Page<User> list(
    @RequestParam(defaultValue = "0") int page,
    @RequestParam(defaultValue = "10") int size,
    @RequestParam(defaultValue = "id") String sortBy
) {
    return userRepository.findAll(PageRequest.of(page, size, Sort.by(sortBy)));
}

Q44. What is Spring Cache abstraction? Medium

@Service
public class UserService {
    
    @Cacheable(value = "users", key = "#id")
    public User findById(Long id) {
        // Called only if cache miss
        return userRepository.findById(id).orElseThrow();
    }
    
    @CacheEvict(value = "users", key = "#user.id")
    public User update(User user) {
        return userRepository.save(user);
    }
    
    @CachePut(value = "users", key = "#result.id")
    public User create(User user) {
        return userRepository.save(user);
    }
}
// Enable: @EnableCaching on @Configuration
// Backend: CaffeineCacheManager, RedisCacheManager, etc.

Q45. What is Spring's JdbcTemplate? Medium

@Repository
public class UserDao {
    @Autowired
    private JdbcTemplate jdbc;
    
    public List<User> findAll() {
        return jdbc.query(
            "SELECT * FROM users",
            (rs, rowNum) -> new User(
                rs.getLong("id"),
                rs.getString("name"),
                rs.getString("email")
            )
        );
    }
    
    public int save(User user) {
        return jdbc.update(
            "INSERT INTO users(name, email) VALUES(?, ?)",
            user.getName(), user.getEmail()
        );
    }
}

Q46. What is @Async in Spring? Advanced

@Configuration
@EnableAsync
public class AsyncConfig { }

@Service
public class EmailService {
    
    @Async
    public Future<Boolean> sendEmail(String to, String subject) {
        // Runs in a separate thread pool thread
        Thread.sleep(500);
        return new AsyncResult<>(true);
    }
    
    @Async
    public CompletableFuture<Boolean> sendEmailAsync(String to, String subject) {
        return CompletableFuture.completedFuture(sendInternal(to, subject));
    }
}

@Async uses AOP proxy - the same self-invocation limitation applies.


Spring Security Basics

Q47. What is Spring Security? Easy

Key concepts:

  • SecurityFilterChain: ordered chain of security filters
  • AuthenticationManager: verifies credentials
  • UserDetailsService: loads user details from storage
  • SecurityContext: holds the authenticated user

Q48. How do you configure basic HTTP security? Medium

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/public/**").permitAll()
                .requestMatchers("/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated()
            )
            .formLogin(Customizer.withDefaults())
            .httpBasic(Customizer.withDefaults())
            .csrf(csrf -> csrf.disable());  // disable for REST APIs
        return http.build();
    }
}

Q49. What is JWT authentication? Advanced

// JWT filter: validate token on every request
public class JwtAuthFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res,
                                    FilterChain chain) throws ServletException, IOException {
        String token = req.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            Claims claims = jwtService.parse(token.substring(7));
            UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
                claims.getSubject(), null, 
                List.of(new SimpleGrantedAuthority("ROLE_USER"))
            );
            SecurityContextHolder.getContext().setAuthentication(auth);
        }
        chain.doFilter(req, res);
    }
}

Q50. What is @PreAuthorize and @Secured? Medium

@EnableMethodSecurity  // required on @Configuration
@RestController
public class AdminController {
    
    @GetMapping("/admin/users")
    @PreAuthorize("hasRole('ADMIN')")
    public List<User> listUsers() { ... }
    
    @DeleteMapping("/users/{id}")
    @PreAuthorize("hasRole('ADMIN') or principal.id == #id")
    public void deleteUser(@PathVariable Long id) { ... }
    
    @GetMapping("/reports")
    @Secured({"ROLE_ADMIN", "ROLE_MANAGER"})
    public List<Report> getReports() { ... }
}

Mock Interview: 5 Questions

  1. Explain the difference between constructor injection and field injection. Which is preferred and why?
  2. A bean marked @Transactional calls another method in the same class that is also @Transactional. Does the second transaction start? Why?
  3. Draw the Spring MVC request flow from when a request hits the server to when the response is returned.
  4. What is the difference between @Component and @Bean? When would you use each?
  5. How would you implement rate limiting for a REST API using Spring MVC interceptors?

FAQ

Q: Should I learn XML configuration or annotation-based configuration? A: Learn annotation-based (Java config + component scanning). XML is legacy. Modern Spring projects use @Configuration, @Bean, and @ComponentScan. Understanding XML is a bonus for maintaining legacy code.

Q: How is Spring Framework different from Spring Boot? A: Spring Framework requires manual configuration of DataSource, MVC setup, transaction management, etc. Spring Boot auto-configures these via @EnableAutoConfiguration based on what's on the classpath. Most real-world projects use Spring Boot, but interviewers still test core Spring Framework concepts.

Q: Is Spring Framework still relevant with Micronaut and Quarkus? A: Yes. Spring remains the dominant Java framework in Indian companies. Micronaut/Quarkus are used for cloud-native microservices where fast startup and low memory are critical, but Spring's ecosystem dominance means most Java jobs still require Spring knowledge.


Related reading: Java Interview Questions 2026 | Spring Boot Interview Questions 2026 | Hibernate Interview Questions 2026 | SQL Interview Questions 2026

Methodology applied to this articlelast verified 8 Jun 2026
Sources used
Public exam-pattern documents, official recruiter pages, and verified candidate reports on r/developersIndia and LinkedIn.
Verification window
Page last edited 8 Jun 2026 by Aditya Sharma. Numbers and patterns sanity-checked against the most recent 2026 cycle drives we tracked.
What we did NOT do
  • No fabricated salary numbers or success rates. If we quote a range, it's sourced.
  • No noun-substituted templates. This article was not generated by swapping company names in a stock prompt.
  • No paid placements, sponsored coaching links, or affiliate-shilled course pushes.
Verification policy: /editorial-standards/. Found something incorrect? Submit a correction - we respond within 48 hours.

Explore this topic cluster

More resources in Interview Questions

Use the category hub to browse similar questions, exam patterns, salary guides, and preparation resources related to this topic.

Paid contributor programme

Sat this this year? Share your story, earn ₹500.

First-person experience reports help future candidates prep smarter. We pay verified contributors ₹500 via UPI per accepted story - with byline.

Submit your story →

Ready to practice?

Take a free timed mock test

Put what you learned into practice. Our mock tests match the 2026 pattern with timer, navigator, reveal, and score breakdown. No signup.

Start Free Mock Test →

Related Articles

More from PapersAdda

Share this guide: