Skip to content
javahacks.dev
Spring Framework

How Spring Container Works and Why Proxies Surprise You

Follow a bean from definition to proxy to destruction, and learn why scopes, proxies and transactions behave the way they do inside the container.

15 min read
Summarize in AI
Flat illustration of a Spring container wiring beans together, with the Spring, Docker, OpenJDK, JUnit5 and Spring Boot logos.

A Spring application is a container, a set of definitions and a lot of wrapping. Understanding those three things explains why @Transactional fails when you call a method on this, why a singleton holds a stale request-scoped bean forever, and why a circular dependency is an error in one setup and silently works in another. This guide opens the container up on Spring Framework 7 and traces one bean through its life, with the failure modes at each stage.

If you are new to the idea of letting a framework hand you your collaborators, start with what dependency injection really is, then come back.

The container reads definitions, not classes

An ApplicationContext holds a registry of bean definitions (core container reference): a class name, a scope, constructor arguments, init and destroy methods and a list of dependencies. A definition comes from component scanning, a @Bean method, an @Import or auto-configuration. The container does not care which.

You can see the registry yourself:

java
try (var context = new AnnotationConfigApplicationContext(AppConfig.class)) {
    for (String name : context.getBeanDefinitionNames()) {
        System.out.println(name + " -> " + context.getBeanDefinition(name).getScope());
    }
}

The same class can appear twice under two names with two sets of arguments. That is why an injection point that matches two definitions throws [NoUniqueBeanDefinitionException](/library/nouniquebeandefinitionexception-fix-qualifier), and one that matches none throws [NoSuchBeanDefinitionException](/library/nosuchbeandefinitionexception-fix-spring).

The life of one singleton

For each singleton, in dependency order, the container runs the same sequence:

  1. Instantiate the object through its constructor, resolving constructor arguments first.
  2. Populate fields and setters marked for injection.
  3. Call Aware callbacks such as BeanNameAware.
  4. Run each BeanPostProcessor.postProcessBeforeInitialization.
  5. Call @PostConstruct, then afterPropertiesSet, then the initMethod.
  6. Run each BeanPostProcessor.postProcessAfterInitialization, which is where proxies are created.
  7. Store the result in the singleton cache.

At shutdown, @PreDestroy and destroyMethod run in reverse dependency order. Because singletons are created eagerly by default, a broken definition fails the startup, and [BeanCreationException](/library/beancreationexception-error-creating-bean-fix-name) is the wrapper you read first. The real cause is at the bottom of its Caused by chain.

Proxies are the product of step six

@Transactional, @Async, @Cacheable and method security work by wrapping your bean in a proxy (proxying mechanisms). Spring creates a JDK dynamic proxy when the bean implements an interface and the configuration asks for it, and a CGLIB subclass otherwise. Spring Boot defaults to CGLIB (spring.aop.proxy-target-class=true).

java
@Service
class InvoiceService {

    @Transactional
    public void create(Invoice invoice) {
        save(invoice);
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void save(Invoice invoice) {
        // intended to run in its own transaction
    }
}

When a controller calls invoiceService.create(...), it holds the proxy, so the transaction begins. Inside create, the call to save is a plain Java call on this. It never touches the proxy, so REQUIRES_NEW is ignored. The full diagnosis is in [@Transactional not working on self-called methods](/library/transactional-not-working-fix-self-called). The fix is to move save to another bean, which also makes the transaction boundary visible in the code.

CGLIB proxies also impose rules: the class cannot be final, and proxied methods cannot be final or private, because the proxy overrides them. A final method on a proxied bean runs against the proxy's uninitialized fields and throws a confusing NullPointerException.

Scopes and the singleton trap

The default scope is singleton: one instance per container. prototype creates a new instance per lookup, and the web scopes (request, session) create one per HTTP request or session.

The trap is injecting a short-lived bean into a long-lived one. A singleton is wired once, so it receives the first request-scoped instance and keeps it. Two safe patterns exist:

java
@Component
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
class RequestContext { /* per-request state */ }

@Service
class Reporter {
    private final ObjectProvider<ReportSession> sessions;

    Reporter(ObjectProvider<ReportSession> sessions) {
        this.sessions = sessions;
    }

    void run() {
        ReportSession session = sessions.getObject(); // fresh prototype each call
    }
}

The scoped proxy defers the lookup to each call. The ObjectProvider makes the lookup explicit. Use the proxy when the code should not know about scope and the provider when it should.

Dependency cycles

With constructor injection, A needing B and B needing A cannot be satisfied, because neither can be built first. Spring reports it at startup as [BeanCurrentlyInCreationException](/library/beancurrentlyincreationexception-fix-spring). Since Spring Boot 2.6, circular references are prohibited by default even for setter injection, which used to hide the design problem. Allowing them again with spring.main.allow-circular-references=true is a patch, not a fix. The real fix is to extract the shared behavior into a third bean. Circular dependencies in Spring Boot covers the options.

Why constructor injection wins

Field injection hides dependencies, prevents final fields and makes the class impossible to construct in a plain unit test without reflection. Constructor injection makes the dependency list the first thing a reader sees and lets the compiler help. If an injection fails, [UnsatisfiedDependencyException](/library/unsatisfieddependencyexception-fix-spring) names the parameter that broke.

What to read when the container surprises you

SymptomFirst thing to check
Annotation has no effectIs the call going through the proxy?
Two beans matchAdd @Qualifier or @Primary, or rename the parameter
Startup fails on a bean you never wroteRead the bottom Caused by
Value never changes between requestsA request-scoped bean injected into a singleton
@Transactional ignoredSelf-invocation, private method, or final class

Build a toy container to see what it does

The quickest way to demystify a container is to write a small one. This is about seventy lines of plain Java, with no Spring in it, that does what the first half of this guide describes: it holds definitions, creates singletons in dependency order through constructors, caches them and lets a post-processor wrap the result:

java
import java.lang.reflect.*;
import java.util.*;
import java.util.function.UnaryOperator;

public class MiniContainer {

    private final Map<Class<?>, Class<?>> definitions = new LinkedHashMap<>();
    private final Map<Class<?>, Object> singletons = new HashMap<>();
    private final Set<Class<?>> inCreation = new HashSet<>();
    private final List<UnaryOperator<Object>> postProcessors = new ArrayList<>();

    public <T> void register(Class<T> type, Class<? extends T> implementation) {
        definitions.put(type, implementation);
    }

    public void addPostProcessor(UnaryOperator<Object> processor) {
        postProcessors.add(processor);
    }

    public void refresh() {
        definitions.keySet().forEach(this::get);          // eager singletons, like Spring
    }

    @SuppressWarnings("unchecked")
    public <T> T get(Class<T> type) {
        Object existing = singletons.get(type);
        if (existing != null) return (T) existing;

        if (!inCreation.add(type)) {
            throw new IllegalStateException("Circular dependency while creating " + type.getSimpleName());
        }
        try {
            Class<?> implementation = definitions.get(type);
            if (implementation == null) {
                throw new IllegalStateException("No bean of type " + type.getName());
            }
            Constructor<?> constructor = implementation.getDeclaredConstructors()[0];
            Object[] args = Arrays.stream(constructor.getParameterTypes()).map(this::get).toArray();
            Object bean = constructor.newInstance(args);          // steps 1 and 2: instantiate and inject
            for (UnaryOperator<Object> processor : postProcessors) {
                bean = processor.apply(bean);                      // step 6: possibly wrap in a proxy
            }
            singletons.put(type, bean);
            return (T) bean;
        } catch (ReflectiveOperationException e) {
            throw new IllegalStateException("Cannot create " + type.getName(), e);
        } finally {
            inCreation.remove(type);
        }
    }
}

Use it with two beans and a post-processor that adds a call log through a JDK dynamic proxy, which is how Spring applies cross-cutting behavior to an interface:

java
interface Greeter { String greet(String name); }

class EnglishGreeter implements Greeter {
    public String greet(String name) { return "Hello, " + name; }
}

class Welcome {
    private final Greeter greeter;
    Welcome(Greeter greeter) { this.greeter = greeter; }
    String message() { return greeter.greet("Ada"); }
}

public class MiniDemo {

    public static void main(String[] args) {
        MiniContainer container = new MiniContainer();
        container.register(Greeter.class, EnglishGreeter.class);
        container.register(Welcome.class, Welcome.class);

        container.addPostProcessor(bean -> {
            Class<?>[] interfaces = bean.getClass().getInterfaces();
            if (interfaces.length == 0) return bean;
            return Proxy.newProxyInstance(bean.getClass().getClassLoader(), interfaces,
                (proxy, method, methodArgs) -> {
                    System.out.println("-> " + method.getName());
                    return method.invoke(bean, methodArgs);
                });
        });

        container.refresh();
        System.out.println(container.get(Welcome.class).message());
        System.out.println(container.get(Greeter.class).getClass().getName());
    }
}

The output shows -> greet, then Hello, Ada, and the last line prints a class named like jdk.proxy1.$Proxy0, not EnglishGreeter. That is the whole trick behind @Transactional, in miniature: the object that was injected into Welcome is the wrapper, and a call on this inside EnglishGreeter would never print the arrow. Try adding a second method on EnglishGreeter that calls greet, call it through the proxy, and watch the inner call go unlogged. The container also detects the cycle if you make two beans need each other, which is the behavior of constructor injection described earlier, in one if.

Watch a real bean being born

Spring exposes every step of the sequence as a hook, so you can print the life of a bean in a real context. This class implements most of them, and a BeanPostProcessor logs the steps that surround initialization:

java
@Component
class Audited implements BeanNameAware, InitializingBean, DisposableBean {

    Audited() { System.out.println("1. constructor"); }

    @Autowired
    void setDependency(Clock clock) { System.out.println("2. injection of " + clock.getClass().getSimpleName()); }

    @Override
    public void setBeanName(String name) { System.out.println("3. aware of its own name: " + name); }

    @PostConstruct
    void postConstruct() { System.out.println("5. @PostConstruct"); }

    @Override
    public void afterPropertiesSet() { System.out.println("6. afterPropertiesSet"); }

    @PreDestroy
    void preDestroy() { System.out.println("9. @PreDestroy"); }

    @Override
    public void destroy() { System.out.println("10. destroy"); }
}

@Component
class Tracer implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String name) {
        if (bean instanceof Audited) System.out.println("4. postProcessBeforeInitialization");
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String name) {
        if (bean instanceof Audited) System.out.println("7. postProcessAfterInitialization (proxy goes here)");
        return bean;
    }
}

Run it in any context that has a Clock bean, and the numbered lines appear in the order of the lifecycle list. Two details are worth noticing. @PostConstruct runs before afterPropertiesSet, which is the order of the list above, and both run after every dependency is injected, so the bean can use them. And the BeanPostProcessor is itself a bean that the container must create first, which is why a post-processor with a dependency on a normal service causes the "not eligible for getting processed by all BeanPostProcessors" message: the service was created before the processors were ready, so it went without its proxy. Declare processors as static @Bean methods and give them as few dependencies as you can.

Ways to fix self-invocation, with their costs

The self-invocation trap appears in the InvoiceService example, and there are four honest ways out. The cleanest is to move the second method to another bean, so the call crosses a proxy:

java
@Service
class InvoiceService {

    private final InvoiceWriter writer;

    InvoiceService(InvoiceWriter writer) { this.writer = writer; }

    @Transactional
    public void create(Invoice invoice) {
        writer.save(invoice);                 // goes through the writer's proxy
    }
}

@Service
class InvoiceWriter {

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void save(Invoice invoice) { /* own transaction */ }
}

This costs one extra class and it makes the boundary visible, which is usually the right trade. The second way is to manage the transaction programmatically where the method is, with TransactionTemplate, which has no proxy to bypass:

java
@Service
class InvoiceService {

    private final TransactionTemplate requiresNew;

    InvoiceService(PlatformTransactionManager manager) {
        this.requiresNew = new TransactionTemplate(manager);
        this.requiresNew.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
    }

    public void create(Invoice invoice) {
        requiresNew.executeWithoutResult(status -> save(invoice));
    }

    private void save(Invoice invoice) { /* inside its own transaction */ }
}

The third is to inject the bean into itself with @Lazy and call through the reference, which works and reads as a trick. The fourth is AopContext.currentProxy() with @EnableAspectJAutoProxy(exposeProxy = true), which ties your class to Spring's AOP API and is the one to avoid. Use the first when the method is a real unit of work, and the second when the transaction logic is part of one method's flow. A related trap is a private or final method with @Transactional: the annotation is silently ignored, because a CGLIB subclass cannot override it.

@Configuration classes and the proxy you did not know about

Another proxy sits in plain sight. A class annotated with @Configuration is subclassed by CGLIB so that calls between its @Bean methods return the container's singleton, not a new object:

java
@Configuration
class AppConfig {

    @Bean
    Clock clock() { return Clock.systemUTC(); }

    @Bean
    PriceCalculator calculator() {
        return new PriceCalculator(clock());     // returns the singleton Clock bean, not a new one
    }

    @Bean
    ReportBuilder reports() {
        return new ReportBuilder(clock());       // the same Clock again
    }
}

If you change the annotation to @Configuration(proxyBeanMethods = false), or to @Component, which is "lite mode", clock() becomes an ordinary method call and both beans get different Clock instances. That can be faster at startup and is correct only when the methods do not call each other. In lite mode, take the dependency as a parameter instead, which is clearer in both modes:

java
@Bean
PriceCalculator calculator(Clock clock) {
    return new PriceCalculator(clock);
}

Spring Boot's own auto-configurations use proxyBeanMethods = false for exactly this reason, and a reasonable rule for application code is to take parameters and never call @Bean methods from each other.

Ordering, laziness and the events around startup

Singletons are created in dependency order, and between unrelated beans the order is not a contract. When one bean needs another to exist first without holding a reference to it, say so with @DependsOn. When creation is expensive and rarely needed, mark it lazy, and the cost moves from startup to the first use:

java
@Component
@Lazy
class PdfRenderer { /* loads fonts, takes a second to build */ }

@Component
@DependsOn("schemaMigrator")
class CatalogCache { /* must not read the database before the migrations ran */ }

Lazy initialization for the whole application, with spring.main.lazy-initialization=true, speeds startup and moves wiring errors from boot to the first request that touches the bean, which defeats the early failure that is one of the container's best features. Use it for developer machines and tests, and be careful in production. To run code once everything is ready, listen for the right event and do not use a @PostConstruct in a bean that others depend on:

java
@Component
class WarmUp {

    @EventListener(ApplicationReadyEvent.class)
    void onReady() {
        // all singletons exist, the web server is accepting connections
    }

    @EventListener(ContextClosedEvent.class)
    void onClose() {
        // the container is shutting down, before beans are destroyed
    }
}

ContextRefreshedEvent fires when the context is fully initialized, ApplicationReadyEvent (Spring Boot) fires after the application runners have completed, and the order matters when a health check must not report ready until the warm-up has finished.

Breaking a cycle you cannot redesign

Constructor cycles are a design signal, and the right fix is to extract the shared part into a third bean that both depend on. When the redesign is not possible this week, @Lazy on one injection point defers the real dependency behind a proxy and lets the container start:

java
@Service
class OrderService {

    private final NotificationService notifications;

    OrderService(@Lazy NotificationService notifications) {
        this.notifications = notifications;
    }
}

The proxy resolves the real bean on its first method call. The cycle still exists in the design, so leave a comment with the ticket for the redesign, since a deferred cycle tends to become permanent. Spring Boot disables circular references by default for a reason: a cycle is a sign that two classes know too much about each other.

Test the container's behavior, not only your classes

Wiring is behavior, and Spring Boot provides a runner that builds small contexts fast, with no web server. It is the right tool to check conditional beans, qualifiers and property binding:

java
class PricingConfigTest {

    private final ApplicationContextRunner runner = new ApplicationContextRunner()
        .withUserConfiguration(PricingConfig.class);

    @Test
    void usesTheFlatRateByDefault() {
        runner.run(context -> assertThat(context).hasSingleBean(FlatRate.class));
    }

    @Test
    void switchesToTieredPricingWhenEnabled() {
        runner.withPropertyValues("shop.pricing.mode=tiered")
              .run(context -> {
                  assertThat(context).hasSingleBean(TieredRate.class);
                  assertThat(context).doesNotHaveBean(FlatRate.class);
              });
    }

    @Test
    void failsWithAClearMessageWhenTheCurrencyIsMissing() {
        runner.withPropertyValues("shop.pricing.mode=tiered", "shop.currency=")
              .run(context -> assertThat(context).hasFailed());
    }
}

Each test builds a context in milliseconds, and the third one asserts that a bad configuration refuses to start, which protects the "fail at startup" promise. Use it for every auto-configuration or conditional bean you write.

Inspect a running container

When you do not own the code, ask the context. In a Spring Boot application, three tools cover almost every question about what exists and why:

Shell
curl -s localhost:8080/actuator/beans | jq '.contexts.application.beans | keys | length'
curl -s localhost:8080/actuator/conditions | jq '.contexts.application.negativeMatches | keys | .[0:5]'
properties
logging.level.org.springframework.beans.factory.support.DefaultListableBeanFactory=DEBUG

The beans endpoint lists every bean with its scope, type and dependencies. conditions shows why an auto-configuration did not apply, and the debug log of the bean factory prints each singleton as it is created, which finds the one that takes four seconds. Expose these endpoints only in a development profile or behind authentication, since they describe your application's internals.

Ahead-of-time processing changes the "when"

The model in this guide says the container reads definitions at startup, and that was accurate for years. With ahead-of-time (AOT) processing, used for GraalVM native images and optionally for faster JVM startup, Spring computes the bean definitions at build time and generates plain Java code that registers them. The practical effects are the same ones Quarkus users know: conditions on beans are evaluated at build time, so a profile or property that decides which bean exists must be known when the application is built, and reflection that Spring cannot see must be declared with hints (@RegisterReflectionForBinding and RuntimeHints). If you stay on the JVM with a normal build, none of this applies, and the container behaves as described above.

A method for diagnosing a container problem

When a Spring application behaves in a way the code does not explain, resist the urge to try fixes. Work through four questions in order, and most problems are located by the second.

First, is this the object the code appears to use? Print the class of the injected bean. A name such as InvoiceService$$SpringCGLIB$$0 or $Proxy53 says the call goes through a proxy, and a plain class name says it does not, so an annotation on it cannot be working. Second, did the call cross the proxy? A call from another bean does, and a call on this does not. Third, which definition won? If there are two candidates, find out which one the container picked and why, with the beans endpoint or by asking for the bean by name. Fourth, when was it created, and with what? A singleton that holds a value from startup will never see a later change, and a bean created before its post-processors were ready has no proxy at all.

The answers are usually dull. A @Transactional method was private. A bean was defined twice, once by scanning and once by an explicit method. A request-scoped value was injected into a singleton, so the first user's data was kept for everyone. Each of these is a statement about the container's model, and none of them needs a debugger once the model is clear. The reason to spend an afternoon with the mini container above is that the model then stays in your head, and the next surprise takes minutes.

Two habits keep surprises rare. Put behavior that depends on a proxy, such as transactions and caching, at the boundary of a bean that other beans call, and keep the internals of a class free of annotations that need the proxy. And treat the startup log as a result. A context that starts cleanly with every bean accounted for is a fact worth having, and a test that builds it, as in the context runner example, turns that fact into something a build can check on every commit.

Where this model stops

The container model above is for a Spring application context on the JVM. It does not describe ahead-of-time processing, where Spring Framework 6 and later can compute the bean definitions at build time for native images, and some of the dynamic features above are restricted. If your service is on that path, the Spring Boot guide covers the practical limits, and Quarkus is built around the same idea from the start.

Also inJava Core
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.