Top 10 Must‑Know Spring Interview Questions for Java Developers

This article walks through the ten most frequently asked Spring interview topics—including IoC/DI concepts, bean lifecycle, AOP mechanics, circular‑dependency resolution, @Transactional behavior, Spring Boot startup steps, auto‑configuration, @Autowired vs @Resource, bean scopes, and the differences between servlet filters and Spring interceptors—providing concrete code examples and key points that can earn interviewers' extra credit.

Coder Trainee
Coder Trainee
Coder Trainee
Top 10 Must‑Know Spring Interview Questions for Java Developers

1. IoC and DI

IoC (Inversion of Control) delegates object creation and dependency management to the Spring container. DI (Dependency Injection) is a concrete implementation of IoC; Spring injects dependencies via constructor, setter, or field annotations such as @Autowired.

// Traditional way
public class OrderService {
    private UserService userService = new UserService();
}

// Spring way
@Service
public class OrderService {
    @Autowired
    private UserService userService;
}

2. Bean lifecycle

Instantiation (new)
→ Property injection (@Autowired / setter)
→ BeanNameAware.setBeanName()
→ BeanFactoryAware.setBeanFactory()
→ ApplicationContextAware.setApplicationContext()
→ BeanPostProcessor.postProcessBeforeInitialization()
→ InitializingBean.afterPropertiesSet()
→ @PostConstruct method
→ init‑method (configured)
→ BeanPostProcessor.postProcessAfterInitialization()
→ …in use…
→ @PreDestroy method
→ DisposableBean.destroy()
→ destroy‑method (configured)

BeanPostProcessor runs both before and after initialization; AOP proxies are created in postProcessAfterInitialization.

3. AOP principle

AOP is implemented with dynamic proxies. If the target class implements an interface, Spring creates a JDK dynamic proxy; otherwise it falls back to CGLIB subclass generation.

1. Spring scans @Aspect classes
2. Matches pointcuts (@Pointcut)
3. Generates proxy (JDK or CGLIB)
4. Method call → executes interceptor chain (MethodInterceptor)

JDK proxy uses Proxy.newProxyInstance; CGLIB generates a subclass via bytecode enhancement. Spring 2.0+ defaults to CGLIB when no interface is present; the behavior can be forced to JDK proxies with spring.aop.proxy-target-class=false.

4. Circular dependency resolution

Spring resolves singleton circular dependencies using a three‑level cache:

Level‑1 (singletonObjects) : fully initialized beans

Level‑2 (earlySingletonObjects) : early‑exposed (partially built) beans

Level‑3 (singletonFactories) : ObjectFactory instances that can create early references

1. Instantiate A → put A's ObjectFactory into level‑3 cache
2. Populate A's properties → discover dependency on B
3. Instantiate B → put B's ObjectFactory into level‑3 cache
4. Populate B's properties → discover dependency on A
5. Retrieve A's early reference from level‑3 → inject into B
6. Complete B initialization → become a full bean
7. Return to A, inject B, and finish A's initialization

Constructor injection cannot break circular dependencies because the instance is needed before any early reference can be exposed. Only singleton beans are supported; prototype beans cannot be resolved this way.

5. @Transactional principle

@Transactional

relies on AOP dynamic proxies. Before the target method executes, the proxy starts a transaction (sets autoCommit=false); after method execution it either commits (on success) or rolls back (on exception).

1. Call method annotated with @Transactional
2. Proxy decides whether to start a transaction
3. Begin transaction (autoCommit = false)
4. Execute target method
5. Success → commit
6. Exception (and rollback conditions met) → rollback

Transaction propagation behaviors:

REQUIRED (default): join existing transaction or create a new one

REQUIRES_NEW : suspend current transaction and start a new one

SUPPORTS : join if a transaction exists; otherwise execute non‑transactionally

NOT_SUPPORTED : execute non‑transactionally, suspending any existing transaction

MANDATORY : must have an existing transaction, else throw an exception

NEVER : must not have a transaction; throws if one exists

NESTED : creates a nested transaction using savepoints

Failure scenarios: internal method calls bypass the proxy, non‑public methods are not proxied, caught exceptions prevent rollback, and only unchecked exceptions trigger rollback by default (checked exceptions require rollbackFor).

6. Spring Boot startup process

SpringApplication.run()
│
├─ Determine application type (SERVLET / REACTIVE / NONE)
├─ Load SpringFactoriesLoader (META-INF/spring.factories)
├─ Create Environment (load config files)
├─ Create IoC container (AnnotationConfig…ApplicationContext)
└─ refresh(container)
    │
    ├─ prepareRefresh()
    ├─ obtainFreshBeanFactory()
    ├─ prepareBeanFactory()
    ├─ invokeBeanFactoryPostProcessors()
    ├─ registerBeanPostProcessors()
    ├─ onRefresh() (start embedded web server)
    ├─ finishBeanFactoryInitialization() (instantiate singleton beans)
    └─ finishRefresh()
refresh()

consists of 12 steps; invokeBeanFactoryPostProcessors processes @ComponentScan and @Bean, while finishBeanFactoryInitialization creates all non‑lazy singleton beans.

7. Auto‑configuration principle

@SpringBootApplication

= @SpringBootConfiguration + @EnableAutoConfiguration + @ComponentScan. The core of @EnableAutoConfiguration is @Import(AutoConfigurationImportSelector.class).

@EnableAutoConfiguration
    │
    ▼
AutoConfigurationImportSelector
    │
    ▼
Load classes listed under EnableAutoConfiguration in META-INF/spring.factories
    │
    ▼
Filter with @Conditional annotations (e.g., @ConditionalOnClass, @ConditionalOnMissingBean, @ConditionalOnProperty)
    │
    ▼
Resulting auto‑configuration classes become active

Since Spring Boot 2.7, spring.factories is being phased out in favor of

META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports

.

8. @Autowired vs @Resource

Source : Spring vs JDK (JSR‑250)

Injection mode : by type (default) vs by name (default)

required attribute : true vs false

Combination : can use @Qualifier with @Autowired; @Resource uses name attribute

Supported locations : constructor, method, field, parameter vs method, field

// @Autowired by type (use @Qualifier for multiple beans of same type)
@Autowired
@Qualifier("userService")
private UserService userService;

// @Resource by name
@Resource(name = "userService")
private UserService userService;

9. Spring bean scopes

singleton (default) : one instance per container; typical for stateless services/DAOs

prototype : a new instance each time the bean is requested; used for stateful beans

request : one instance per HTTP request; used in web request handling

session : one instance per HTTP session; used for session‑scoped data

application : one instance per ServletContext; used for application‑wide resources

websocket : one instance per WebSocket connection; used for WebSocket handling

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

Singleton beans are fully managed by the IoC container, including destruction. Prototype beans are created by the container but not destroyed automatically. Web scopes require registration of RequestContextListener or RequestScope.

10. Filter vs Interceptor

Specification : Servlet specification vs Spring framework

Execution timing : before/after servlet processing vs before/after controller method

Context access : only ServletContext vs can access any Spring bean

Typical use : encoding, authentication, logging at servlet level vs authorization, logging, transaction handling at controller level

Request → Filter (pre‑Servlet) → DispatcherServlet → Interceptor (pre‑controller) → Controller
                                            │
                                            ▼
Response ← Filter (post‑Servlet) ← DispatcherServlet ← Interceptor (post‑controller)

Spring's HandlerInterceptor can inject other beans, while a Filter cannot. Since Spring 3.0 there are also MethodInterceptor instances at the AOP layer for different use cases.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaAOPIoCSpringSpring BootDependency InjectionTransaction ManagementBean Scope
Coder Trainee
Written by

Coder Trainee

Experienced in Java and Python, we share and learn together. For submissions or collaborations, DM us.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.