Skip to main content
PreparationZone Logo
PrepZone

The IoC Container and Spring Beans

How the ApplicationContext creates, wires and manages your objects.

Pass checkpoint below

Why this matters

  • Every @Service, @Repository, and @Controller in BookStore is a bean managed by the container — not created with new.
  • Misunderstanding bean lifecycle leads to NullPointerException from field injection or duplicate instances from manual construction.
  • Container internals are a core Spring interview topic; explaining bean creation order demonstrates real framework knowledge.

Bean = container-managed object

L1 · Fresher

Spring constructs BookService, injects BookRepository, and stores the instance in the ApplicationContext. You ask for types with @Autowired constructor parameters instead of calling new.

ApplicationContext responsibilities

L2 · Intermediate

The context reads bean definitions (annotations, @Bean methods), resolves dependency order, and publishes lifecycle events. getBean is for frameworks and tests — prefer injection in app code.

Circular dependencies

L3 · Advanced

Constructor cycles fail fast at startup with BeanCurrentlyInCreationException. Fix by redesigning boundaries, @Lazy on one side, or setter injection only when justified.

BeanFactory vs ApplicationContext

L4 · Expert

BeanFactory is the low-level registry; ApplicationContext adds internationalization, events, and resource loading. Boot uses an application context implementation specialized for servlet and reactive stacks.

What is a bean?

A bean is any object whose lifecycle Spring controls. For BookStore:

Java
// learn:fragment
@Service
public class BookService {
    private final BookRepository repository;

    public BookService(BookRepository repository) {
        this.repository = repository;
    }
}

Spring instantiates BookService once, injects the BookRepository bean, and reuses that same instance for every HTTP request.

Bean registration methods

  • Component scanning — @Service, @Component, @Repository, @Controller on a class.
  • @Bean methods — Explicit factory methods inside @Configuration classes.
  • Auto-configuration — Boot creates beans like DataSource when starters are on the classpath.
ApplicationContext
BookController@RestController
BookService@Service
BookRepository@Repository
DataSourceAuto-configured

Arrows show @Autowired wiring — container injects at startup

The ApplicationContext reads configuration, creates beans, and wires dependencies automatically.

ApplicationContext vs BeanFactory

BeanFactory is the low-level interface for bean retrieval. ApplicationContext extends it with:

ApplicationContext extras

  • Automatic BeanPostProcessor registration
  • Message source internationalisation
  • Event publication (ApplicationEventPublisher)
  • Resource loading from classpath

Boot uses AnnotationConfigServletWebServerApplicationContext — you never instantiate it directly.

Bean definition and creation

At startup the container processes bean definitions — metadata describing how to build each bean:

Bean creation pipeline

  1. Scan — Find @Component classes in com.example.bookstore.**
  2. Parse — Read constructor parameters as injection points
  3. Sort — Order beans to satisfy dependencies (topological sort)
  4. Instantiate — Call constructors, apply @Autowired where needed
  5. Initialise — Run @PostConstruct, InitializingBean.afterPropertiesSet()
  6. Register — Store in the singleton cache

If BookService depends on BookRepository which depends on DataSource, the container creates them in that order automatically.

Retrieving beans programmatically

Rarely needed in application code, but useful in tests:

Java
// learn:fragment
@SpringBootTest
class BeanInspectionTest {
    @Autowired
    private ApplicationContext context;

    @Test
    void bookServiceIsSingleton() {
        BookService a = context.getBean(BookService.class);
        BookService b = context.getBean(BookService.class);
        assertSame(a, b);
    }
}

Both references point to the same object — default scope is singleton.

When the container fails

Circular dependencies crash startup:

Java
// learn:fragment
@Service
public class OrderService {
    public OrderService(BookService bookService) { ... }
}

@Service
public class BookService {
    public BookService(OrderService orderService) { ... }  // cycle!
}

Spring detects the cycle and throws BeanCurrentlyInCreationException. Fix by restructuring dependencies or using @Lazy on one side.

Bean naming

Default bean name is the decapitalised class name: bookService for BookService. Override with @Service("catalogService") when multiple implementations exist.

Java
// learn:fragment
public interface BookRepository { ... }

@Repository
public class JpaBookRepository implements BookRepository { ... }

Injection by type works when only one implementation exists. Multiple implementations require @Qualifier or @Primary.

Context refresh and shutdown

In production the context starts once and runs until shutdown. @PreDestroy methods clean up resources:

Java
// learn:fragment
@Service
public class CacheWarmupService {
    @PreDestroy
    public void shutdown() {
        // flush pending cache writes
    }
}

Boot registers a shutdown hook so SIGTERM triggers graceful bean destruction.

Bean lifecycle

For a singleton BookService, the container walks a fixed sequence. Remembering the order explains why @Autowired fields are null inside the constructor and why an AOP proxy exists only after initialization.

From definition to destruction

  1. Load the definition — Component scan or a @Bean method records the class, scope, and dependencies. Nothing is constructed yet.
  2. Instantiate — The container calls the constructor and supplies constructor arguments. This is the only moment final dependencies can be set.
  3. Populate — Setter and field injection run. Prefer not to need this step.
  4. Aware callbacks — BeanNameAware, BeanFactoryAware, and ApplicationContextAware if you implemented them.
  5. Before-init post-processors — BeanPostProcessor.postProcessBeforeInitialization.
  6. Initialize — @PostConstruct, then InitializingBean.afterPropertiesSet.
  7. After-init post-processors — postProcessAfterInitialization. Spring AOP wraps the bean in a proxy here. Callers must use that proxy, not the raw instance.
  8. Ready — The singleton is stored in the context and injected into other beans.
  9. Destroy — On shutdown, @PreDestroy then DisposableBean.destroy. Prototype beans skip this; you destroy those yourself.
Java
// learn:fragment
@Service
public class BookService {
    private final BookRepository books;

    public BookService(BookRepository books) {
        this.books = books; // step 2 — repository is already created
    }

    @PostConstruct
    void ready() {
        // step 6 — safe to use dependencies
    }

    @PreDestroy
    void shutdown() {
        // step 9 — context is closing
    }
}

Inversion of control is this sequence applied to every bean: your classes declare what they need, and the container decides when they are created, wired, and destroyed.

Quick recall

Everything you need if you only revisit this box.

  • Beans are objects whose lifecycle and dependencies the ApplicationContext manages.
  • Default scope is singleton — one instance per application context.
  • Registration via component scanning (@Service) or explicit @Bean methods.
  • The container topologically sorts dependencies and fails fast on circular references.
  • Never use new for Spring-managed services; injection provides wired instances.
  • ApplicationContext extends BeanFactory with events, resources, and post-processors.

Test yourself

Answer these before moving on — recall is what makes it stick.

Checkpoint quiz

Pass 6 of 9 to verify this article on your path — scrolling alone does not count.

Question 1 of 9

BookStore on-call: a junior says "Bean = container-managed object" is only theory. What do you correct them with?