Chaturmind
LearnDSASystem DesignInterview PrepDevOpsEngineering GrowthBlog
Start learning
Chaturmind

Structured learning paths for engineers who want to go deep. Written by practitioners.

Learn

  • Java
  • DSA
  • System Design
  • Spring Boot
  • AI / ML
  • DevOps
  • Engineering Growth
  • Java Interview Prep

Company

  • Blog
  • Contact

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Chaturmind. All rights reserved.

Built for engineers who want to go deep.


← Java Interview Prep: 2–5 Years

Revise the Fresher Tier

  • Revise: Core Java Fundamentals (Fresher Tier)
  • Revise: Collections, Threads, Java 8 & Coding (Fresher Tier)
  • Revise: Spring Core, Spring Boot & Spring MVC (Fresher Tier)
  • Revise: Hibernate, SQL, Microservices, Maven & Git (Fresher Tier)

Intermediate Core Java

  • Intermediate OOP & Language Features — Interview Questions
  • Enums, Generics, Pass-by-Value & Imports — Interview Questions
  • Collections Internals & Scenarios — Interview Questions
  • JVM, Memory & Class Loading — Interview Questions
  • Exception Design & Serialization Edge Cases — Interview Questions

Java 8 Deep Dive & Stream Coding

  • Lambdas, Functional Interfaces & Method References — Interview Questions
  • Default Methods, Backward Compatibility & Optional — Interview Questions
  • Stream API Internals (Part 1) — Interview Questions
  • Stream API Internals (Part 2) — Interview Questions
  • Stream Coding Problems (Level 2, Part 1) — Interview Questions
  • Stream Coding Problems (Level 2, Part 2) — Interview Questions

Concurrency & Multithreading

  • Synchronization, Locks & Deadlocks — Interview Questions
  • Executors, ThreadLocal & Concurrent Collections — Interview Questions

Spring Framework In Depth

  • Bean Lifecycle, Contexts & Circular Dependencies — Interview Questions
  • Spring Bean Conflicts, AOP, Batch & Injection Styles — Interview Questions

Spring Boot In Depth & Scenarios

  • Spring Boot Internals & Auto-Configuration — Interview Questions
  • Spring Boot Configuration, Profiles & Secrets — Interview Questions
  • Spring Boot Data, Transactions & Caching — Interview Questions
  • Spring Boot Testing, Error Pages & Deployment — Interview Questions
  • Spring Boot Performance, Scaling & Resilience — Interview Questions
  • Spring Boot Async, Events & Messaging — Interview Questions
  • Spring Boot Security Scenarios — Interview Questions
  • Actuator, AOP, Spring Cloud & Distributed Tracing — Interview Questions
  • External APIs, Files, GraphQL & WebFlux — Interview Questions

Spring Security

  • Spring Security — OAuth2, CORS, CSRF & Access Rules — Interview Questions
  • Spring Security — Passwords, Filter Chain, Sessions & Debugging — Interview Questions

Apache Kafka

  • Kafka Architecture, Topics & ZooKeeper vs KRaft — Interview Questions
  • Kafka Producers, Consumers, Reliability & Streams — Interview Questions
  • Kafka Security, Connect & Core Scenarios — Interview Questions
  • Kafka Production Scenarios — Interview Questions

Git, Maven & Gradle (Level II)

  • Git Workflows, Rebase & Conflict Handling — Interview Questions
  • Git Recovery, Hooks, Tags & Collaboration — Interview Questions
  • Maven Builds, Multi-Module Projects & Dependency Resolution — Interview Questions
  • Maven Profiles, settings.xml, Plugins & Quality Gates — Interview Questions
  • Gradle Fundamentals, Migration & Dependencies — Interview Questions
  • Gradle Performance, Plugins, Testing & Publishing — Interview Questions

Deployment & CI/CD

  • Sessions, CI/CD Pipelines, Rollbacks & Secrets — Interview Questions
  • Migrations, Zero-Downtime Releases, Containers & Monitoring — Interview Questions

JUnit 5 & Mockito

  • JUnit 5 — Interview Questions
  • Mockito Basics — Interview Questions
  • Mockito Advanced & Tricky Questions — Interview Questions
Chaturmind
← Java Interview Prep: 2–5 Years

Revise the Fresher Tier

  • Revise: Core Java Fundamentals (Fresher Tier)
  • Revise: Collections, Threads, Java 8 & Coding (Fresher Tier)
  • Revise: Spring Core, Spring Boot & Spring MVC (Fresher Tier)
  • Revise: Hibernate, SQL, Microservices, Maven & Git (Fresher Tier)

Intermediate Core Java

  • Intermediate OOP & Language Features — Interview Questions
  • Enums, Generics, Pass-by-Value & Imports — Interview Questions
  • Collections Internals & Scenarios — Interview Questions
  • JVM, Memory & Class Loading — Interview Questions
  • Exception Design & Serialization Edge Cases — Interview Questions

Java 8 Deep Dive & Stream Coding

  • Lambdas, Functional Interfaces & Method References — Interview Questions
  • Default Methods, Backward Compatibility & Optional — Interview Questions
  • Stream API Internals (Part 1) — Interview Questions
  • Stream API Internals (Part 2) — Interview Questions
  • Stream Coding Problems (Level 2, Part 1) — Interview Questions
  • Stream Coding Problems (Level 2, Part 2) — Interview Questions

Concurrency & Multithreading

  • Synchronization, Locks & Deadlocks — Interview Questions
  • Executors, ThreadLocal & Concurrent Collections — Interview Questions

Spring Framework In Depth

  • Bean Lifecycle, Contexts & Circular Dependencies — Interview Questions
  • Spring Bean Conflicts, AOP, Batch & Injection Styles — Interview Questions

Spring Boot In Depth & Scenarios

  • Spring Boot Internals & Auto-Configuration — Interview Questions
  • Spring Boot Configuration, Profiles & Secrets — Interview Questions
  • Spring Boot Data, Transactions & Caching — Interview Questions
  • Spring Boot Testing, Error Pages & Deployment — Interview Questions
  • Spring Boot Performance, Scaling & Resilience — Interview Questions
  • Spring Boot Async, Events & Messaging — Interview Questions
  • Spring Boot Security Scenarios — Interview Questions
  • Actuator, AOP, Spring Cloud & Distributed Tracing — Interview Questions
  • External APIs, Files, GraphQL & WebFlux — Interview Questions

Spring Security

  • Spring Security — OAuth2, CORS, CSRF & Access Rules — Interview Questions
  • Spring Security — Passwords, Filter Chain, Sessions & Debugging — Interview Questions

Apache Kafka

  • Kafka Architecture, Topics & ZooKeeper vs KRaft — Interview Questions
  • Kafka Producers, Consumers, Reliability & Streams — Interview Questions
  • Kafka Security, Connect & Core Scenarios — Interview Questions
  • Kafka Production Scenarios — Interview Questions

Git, Maven & Gradle (Level II)

  • Git Workflows, Rebase & Conflict Handling — Interview Questions
  • Git Recovery, Hooks, Tags & Collaboration — Interview Questions
  • Maven Builds, Multi-Module Projects & Dependency Resolution — Interview Questions
  • Maven Profiles, settings.xml, Plugins & Quality Gates — Interview Questions
  • Gradle Fundamentals, Migration & Dependencies — Interview Questions
  • Gradle Performance, Plugins, Testing & Publishing — Interview Questions

Deployment & CI/CD

  • Sessions, CI/CD Pipelines, Rollbacks & Secrets — Interview Questions
  • Migrations, Zero-Downtime Releases, Containers & Monitoring — Interview Questions

JUnit 5 & Mockito

  • JUnit 5 — Interview Questions
  • Mockito Basics — Interview Questions
  • Mockito Advanced & Tricky Questions — Interview Questions
HomeLearnJava Interview PrepJava Interview Prep: 2–5 YearsSpring Framework In Depth
✓ FreeIntermediate· 8 min read

Bean Lifecycle, Contexts & Circular Dependencies — Interview Questions

The Spring bean lifecycle step by step and why it matters at scale, ApplicationContext vs BeanFactory (and when to use each), circular dependencies and how Boot handles them, @Component vs @Service, JpaRepository vs CrudRepository, @Qualifier vs @Primary, @Transactional essentials, profiles and environment-variable injection.

Published September 25, 2026


How to use this lesson

At this level, Spring questions are about how the container behaves: the order of lifecycle callbacks, why proxies matter, and what Boot does when things conflict. Tie each answer to a production concern: startup failures, missing transactions, the wrong bean injected.

Q1. Explain the Spring bean lifecycle, and why it matters in a large application.

Short answer: For a singleton bean, the container:

  1. Instantiates it (constructor injection happens here).
  2. Populates its properties (setter and field injection).
  3. Calls the Aware callbacks (BeanNameAware, ApplicationContextAware…).
  4. Runs BeanPostProcessor.postProcessBeforeInitialization.
  5. Calls the init callbacks: @PostConstruct → InitializingBean.afterPropertiesSet() → a custom initMethod.
  6. Runs postProcessAfterInitialization, where AOP proxies are created.
  7. The bean is ready. SmartInitializingSingleton and ApplicationReadyEvent follow.
  8. On shutdown, the destroy callbacks run: @PreDestroy → DisposableBean.destroy() → a custom destroyMethod.

Why it matters:

  • Proxies are created in step 6. Code that runs in the constructor or @PostConstruct calls the raw object, so @Transactional/@Async don't apply there yet.
  • Startup time: heavy work in @PostConstruct slows every deployment. Use lazy initialisation, or ApplicationRunner, for optional warm-ups.
  • Graceful shutdown: releasing connections and flushing buffers belongs in @PreDestroy.
  • Prototype beans never get destroy callbacks.

Learn it in depth → Bean Lifecycle in Detail

Q2. What are the differences between ApplicationContext and BeanFactory?

Short answer: BeanFactory is the basic IoC container. It creates beans lazily on request, and supports DI. ApplicationContext extends it, adding:

  • eager singleton creation (fail fast at startup);
  • automatic registration of BeanPostProcessors and BeanFactoryPostProcessors, which is what makes @Autowired, @Value, AOP and @Transactional work;
  • event publishing;
  • MessageSource (i18n);
  • resource loading and Environment/profiles.

Q3. When would you use BeanFactory, and when ApplicationContext?

Short answer: Use ApplicationContext in practically every application. Spring Boot always creates one. A bare BeanFactory makes sense only in very constrained environments, or in framework code that needs minimal, lazy bean management. Even then, you usually still interact with it through the context (context.getBeanFactory()), for example to register beans programmatically.

Q4. What is a circular dependency?

Short answer: Bean A needs bean B, and bean B (directly or through a chain) needs A. With constructor injection, Spring can't create either one first, so startup fails with BeanCurrentlyInCreationException ("Is there an unresolvable circular reference?"). It isn't a runtime deadlock. It's a creation-order problem detected at startup.

Key points to cover:

  • Since Spring Boot 2.6, circular references are prohibited by default, even for field and setter injection. The escape hatch is spring.main.allow-circular-references=true, but it's discouraged.

Q5. What ways does Spring Boot offer to resolve circular dependencies?

Short answer: In order of preference:

  1. Redesign. Extract the shared logic into a third bean that both depend on, or replace the back-reference with an event (ApplicationEventPublisher).
  2. Inject a lazy proxy: @Lazy on one constructor parameter, or ObjectProvider<B>, resolved when first used.
  3. Setter or field injection plus allow-circular-references=true. This works through Spring's early singleton references, but it's a legacy crutch.
@Service
class OrderService {
    private final ObjectProvider<InvoiceService> invoices;          // resolved lazily, which breaks the creation cycle
    OrderService(ObjectProvider<InvoiceService> invoices) { this.invoices = invoices; }
    void complete(Order o) { invoices.getObject().issueFor(o); }
}

Common trap: presenting setter injection as "the fix". On modern Boot it doesn't even start without the opt-in flag, and the cycle usually means the classes have mixed responsibilities.

Q6. What's the difference between @Component and @Service? Are they interchangeable?

Short answer: @Service is a specialisation of @Component (it's meta-annotated with it), so both register a bean through component scanning, and they're technically interchangeable. @Service communicates that the class is business-layer logic. That helps readers, AOP pointcuts (@within(org.springframework.stereotype.Service)) and architecture tests. (@Repository, unlike @Service, also adds exception translation.)

Q7. What's the difference between JpaRepository and CrudRepository, and when would you use CrudRepository?

Short answer: The hierarchy is CrudRepository → ListCrudRepository → JpaRepository, with PagingAndSortingRepository alongside.

  • CrudRepository gives generic CRUD operations: save, findById, findAll, delete, count, existsById.
  • JpaRepository adds JPA-specific operations: flush, saveAndFlush, batch deletes (deleteAllInBatch), getReferenceById, and List return types. It also includes paging and sorting, and query-by-example.

When to prefer CrudRepository:

  • When you want the repository contract to stay store-agnostic. The same interface style works for Spring Data MongoDB, Redis and JDBC.
  • When you want to expose only a minimal API to callers. Or go further, and extend the plain Repository interface, declaring only the methods you need.

Q8. What's the difference between @Qualifier and @Primary? (And again: are @Component and @Service interchangeable?)

Short answer:

  • @Primary marks the default bean when several beans match a type.
  • @Qualifier("name") at the injection point explicitly chooses one, and it overrides @Primary.

Use @Primary for "normally use this one", and @Qualifier for "here I specifically need that one". (On the second part: yes, @Component and @Service are interchangeable technically. @Service just documents the layer.)

@Bean @Primary PaymentGateway razorpay() { … }
@Bean PaymentGateway stripe() { … }

@Service
class RefundService {
    RefundService(PaymentGateway gateway,                                 // → razorpay (the primary)
                  @Qualifier("stripe") PaymentGateway international) { … }   // → stripe
}

Key points to cover:

  • You can also inject all implementations (List<PaymentGateway>, Map<String, PaymentGateway>), and pick one at runtime: the strategy pattern.

Q9. How is @Transactional used?

Short answer: Put @Transactional on a public method of a Spring bean, usually in the service layer. Spring's proxy begins a transaction before the method, commits if it returns normally, and rolls back on RuntimeException or Error.

@Service
class CheckoutService {
    @Transactional                                             // one unit of work
    public Order placeOrder(Cart cart) {
        Order order = orders.save(Order.from(cart));
        inventory.reserve(cart.items());                       // throws → everything rolls back
        return order;
    }
    @Transactional(readOnly = true)
    public List<OrderSummary> history(long customerId) { … }
}

Key points to cover:

  • Checked exceptions don't roll back unless you set rollbackFor.
  • Self-invocation (calling a @Transactional method from another method of the same bean) bypasses the proxy, so no transaction is started.
  • Propagation: REQUIRED (the default) joins an existing transaction, and REQUIRES_NEW suspends it and starts a new one. Isolation and timeout are configurable.
  • Keep transactions short. Don't call slow remote APIs inside them.

Learn it in depth → @Transactional Deep Dive

Q10. What are Spring profiles, and how do you start an application with one?

Short answer: Profiles are named groups of configuration and beans (dev, test, prod) that are activated per environment. Beans can carry @Profile, and properties can live in application-{profile}.yml. Activate them with any of:

  • --spring.profiles.active=prod (a command-line argument);
  • -Dspring.profiles.active=prod (a system property);
  • SPRING_PROFILES_ACTIVE=prod (an environment variable, the usual choice in containers);
  • @ActiveProfiles in tests.

Key points to cover:

  • Spring Boot 2.4+ supports profile groups (spring.profiles.group.prod=db,metrics) and spring.config.activate.on-profile inside multi-document YAML files.

Q11. How do you inject properties from environment variables?

Short answer: Spring's Environment already includes the OS environment variables, so @Value("${DB_PASSWORD}") works. Better still, rely on relaxed binding: the environment variable PAYMENTS_BASE_URL automatically binds to the property payments.base-url, and so to a @ConfigurationProperties class.

@ConfigurationProperties(prefix = "payments")
record PaymentProperties(URI baseUrl, Duration timeout) { }
// export PAYMENTS_BASE_URL=https://api.pay.example  PAYMENTS_TIMEOUT=3s
spring:
  datasource:
    password: ${DB_PASSWORD}          # placeholder resolved from the environment
    url: ${DB_URL:jdbc:postgresql://localhost:5432/shop}   # with a default

Key points to cover:

  • Keep secrets out of files. Inject them through environment variables or a secrets manager (Vault, AWS Secrets Manager), and make sure they don't show up in /actuator/env (Boot masks sensitive keys by default).

Follow-up questions this topic invites — and their answers

Q: What's the difference between BeanPostProcessor and BeanFactoryPostProcessor? A: A BeanFactoryPostProcessor modifies bean definitions before any bean is created (for example, resolving property placeholders). A BeanPostProcessor modifies bean instances after creation (for example, wrapping them in AOP proxies, or processing @Autowired).

Q: Why doesn't @Transactional work on private methods? A: Spring's proxy-based AOP can only intercept calls that go through the proxy, to methods it can override. Private methods can't be overridden, and they're called internally anyway.

Q: How do you run code after the application is fully started? A: Use an ApplicationRunner or CommandLineRunner, or @EventListener(ApplicationReadyEvent.class). That's better than @PostConstruct for work that needs the whole context (and the server) to be ready.

Q: What does @DependsOn do? A: It forces initialisation order when a bean relies on another's side effects rather than on a direct reference, for example a schema migrator that must run before a cache warmer. Prefer explicit dependencies where possible.

Previous

Executors, ThreadLocal & Concurrent Collections — Interview Questions

Next

Spring Bean Conflicts, AOP, Batch & Injection Styles — Interview Questions

AI Tutor

Lesson: Bean Lifecycle, Contexts & Circular Dependencies — Interview Questions

Quick actions

AI responses can be inaccurate. Verify critical information.