Skip to content
Commitwise
Menu
Java Backend

Spring under the hood: beans, scopes and proxies

What the Spring container does between reading your classes and serving the first request, why singletons must be stateless, how prototype and request scopes break when injected into singletons, and why @Transactional, @Cacheable and @Async stop working on self-calls, in Java and Kotlin.

intermediate

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

Two bugs from the same week. A @Cacheable price lookup never hits the cache, although the annotation is right there. And a shopping cart, carefully marked @Scope("prototype") so every checkout gets its own, turns out to be shared by every customer.

Neither is a Spring bug. Both come from how the container builds objects: what it creates, how many times, and what it hands out instead of your object. These are also the Spring questions interviewers ask most, right after “what is dependency injection”.

New to some of these? Open what you need, or skip ahead.

Basics:What is a Spring bean?

A bean is an object that Spring creates and manages for you. Classes marked @Component, @Service, @Repository or @RestController, and objects returned by @Bean methods, become beans. Spring creates them at startup, passes them to each other through constructors (dependency injection), and keeps them in the application context until the app shuts down.

The Spring Boot Basics lesson shows how to declare and inject beans.

Basics:What is a proxy?

A proxy is a stand-in object with the same methods as the real one. Callers talk to the proxy; the proxy does something extra (start a transaction, check a cache, log the time) and then calls the real object. Because it looks exactly like the original, the caller doesn’t notice the difference.

Basics:What is a thread-safe object?

On a server, many requests run at the same time, each on its own thread. An object is thread-safe if several threads can use it at once without corrupting its data. The simplest way to get there: don’t keep changing data in the object’s fields at all. Objects without changing fields are called stateless.

Part Not started

How the container builds a bean

Think of a restaurant kitchen before opening. The chef doesn’t cook each dish from scratch when the first guest arrives: the stations are set up in a fixed order, ingredients are delivered to the right station, every station checks its equipment, and only then are the doors opened.

Spring does the same with your beans when the application starts:

  1. Read the plan. It finds every bean definition (scanned @Component classes, @Bean methods, auto-configuration).
  2. Create each bean by calling its constructor, passing the beans it depends on.
  3. Initialize it: methods marked @PostConstruct run now, when every dependency is already there.
  4. Wrap it if needed: for @Transactional, @Cacheable or @Async, Spring puts a proxy around the bean, and the proxy is what other beans receive.
  5. Use it for the whole life of the application.
  6. Clean up on shutdown: methods marked @PreDestroy run, so connections and files are closed.

The container works in two phases. First it collects bean definitions (metadata: class, scope, dependencies, factory method), and runs BeanFactoryPostProcessors, which may change definitions before any bean exists (property placeholder resolution, @Configuration class processing and auto-configuration conditions work at this level). Then it instantiates singletons in dependency order: constructor, field and setter injection, *Aware callbacks, BeanPostProcessor.postProcessBeforeInitialization (where @PostConstruct is invoked by a high-priority processor), InitializingBean.afterPropertiesSet, custom init methods, and finally postProcessAfterInitialization, where the auto-proxy creator replaces the bean with an AOP proxy if any advice applies. Destruction runs in reverse dependency order: @PreDestroy, DisposableBean.destroy, destroy methods, but only for beans whose lifecycle the container owns (not prototypes).

Interview follow-ups live at the edges: why a bean must not call its own proxied methods during initialization, why circular dependencies are rejected by default since Spring Boot 2.6, and where to start work that needs a fully started application (SmartLifecycle, ApplicationReadyEvent). The Detailed version covers them.

@Component
class PriceFeed(private val client: FeedClient) {   // 1. created, dependencies passed in
    private lateinit var subscription: Subscription

    @PostConstruct
    fun connect() {                                  // 2. initialized: client is ready to use
        subscription = client.subscribe("EUR/USD")
    }

    @PreDestroy
    fun disconnect() {                               // 3. on shutdown: release the resource
        subscription.cancel()
    }
}
@Component
public class PriceFeed {
    private final FeedClient client;
    private Subscription subscription;

    public PriceFeed(FeedClient client) {        // 1. created, dependencies passed in
        this.client = client;
    }

    @PostConstruct
    void connect() {                              // 2. initialized: client is ready to use
        subscription = client.subscribe("EUR/USD");
    }

    @PreDestroy
    void disconnect() {                           // 3. on shutdown: release the resource
        subscription.cancel();
    }
}

Why not open the subscription in the constructor? You could, since constructor injection already gives you client. But @PostConstruct makes the order explicit, keeps the constructor fast and simple (easy to test), and pairs naturally with @PreDestroy. The rule that matters most: anything you open, close in @PreDestroy, or every restart in tests and every redeploy leaks connections.

Predict the output

A bean prints a line in its constructor, in an @Autowired setter, in a @PostConstruct method and in afterPropertiesSet() (it implements InitializingBean). In which order do the lines appear?

@Component
class Probe : InitializingBean {
    init { println("constructor") }

    @Autowired
    fun setClock(clock: Clock) { println("setter") }

    @PostConstruct
    fun init() { println("@PostConstruct") }

    override fun afterPropertiesSet() { println("afterPropertiesSet") }
}
@Component
class Probe implements InitializingBean {
    Probe() { System.out.println("constructor"); }

    @Autowired
    void setClock(Clock clock) { System.out.println("setter"); }

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

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

Starting work too early

Spot the bugA consumer that reads messages before the app is ready

Tap the line with the bug.

@Component
class OrderListener(
    private val queue: OrderQueue,
    private val orders: OrderService,
) {
    init {
        Thread { queue.consume(orders::handle) }.start()
    }
}
@Component
public class OrderListener {
    private final OrderQueue queue;
    private final OrderService orders;

    public OrderListener(OrderQueue queue, OrderService orders) {
        this.queue = queue;
        this.orders = orders;
        new Thread(() -> queue.consume(orders::handle)).start();
    }
}

Circular dependencies

If A needs B in its constructor and B needs A, there’s no order in which both can be created. With field injection, older Spring versions resolved cycles by injecting an early, not yet initialized reference, which hid design problems and broke when proxies were involved (B got the raw A, not its transactional proxy). Since Spring Boot 2.6, circular references are prohibited by default and startup fails with a description of the cycle. spring.main.allow-circular-references=true brings back the old behavior, but the fix is structural: extract the shared logic into a third bean, publish an event instead of calling back, or, as a last resort, inject ObjectProvider<A> and resolve lazily.

Extension points worth knowing

  • BeanFactoryPostProcessor changes bean definitions before any bean is created (register beans programmatically, rewrite properties). It must not request beans itself, or they’re created too early and miss post-processing.
  • BeanPostProcessor sees each bean instance after creation and can return a different object, which is how proxies replace beans. A bean that a post-processor depends on is created before the post-processors are registered and logs “is not eligible for getting processed by all BeanPostProcessors”: it won’t get its @Transactional proxy.
  • SmartLifecycle (with a phase) starts components after all singletons exist and stops them in reverse order on shutdown; graceful shutdown (server.shutdown=graceful) uses the same phases to drain requests.
  • Lazy initialization (spring.main.lazy-initialization=true, @Lazy) speeds up startup but moves configuration errors from startup to the first request.
Deep diveWhy a BeanFactoryPostProcessor @Bean method should be staticInterview favorite

@Bean methods live on a @Configuration class, which is itself a bean. To call a non-static @Bean method, Spring must create the configuration class first. For a BeanFactoryPostProcessor, that’s a problem: post-processors run before ordinary beans are created, so creating the configuration class this early means it (and anything it injects) misses later processing, like @Autowired fields and @Value resolution.

Declaring the method static lets Spring call it without an instance of the configuration class. That’s why PropertySourcesPlaceholderConfigurer beans are traditionally declared with static @Bean, and why Spring logs a warning when a non-static @Bean method returns a BeanFactoryPostProcessor.

  • Two phases: bean definitions (changed by BeanFactoryPostProcessors, conditions evaluated) then instances: constructor, injection, *Aware, @PostConstruct / afterPropertiesSet / init method, then postProcessAfterInitialization, where AOP proxies replace beans.
  • Shutdown in reverse dependency order: @PreDestroy, destroy(); never for prototypes.
  • Start background work on ApplicationReadyEvent or with SmartLifecycle, not in constructors. Circular references fail by default since Boot 2.6: fix the design.

Check this part

  1. Where should a bean open a connection that needs its injected dependencies?

  2. A bean starts a background thread in its constructor. What's the problem?

  3. At which point does a @Transactional bean get replaced by its proxy?

  4. Bean A injects B in its constructor and B injects A. What happens in a current Spring Boot app?

At startup Spring reads bean definitions, creates each bean, injects its dependencies, runs @PostConstruct, and lets post-processors wrap it in proxies before anyone gets it. On shutdown it runs @PreDestroy. Do initialization that needs dependencies in @PostConstruct, and start background work only when the application is ready.

Part Not started

Scopes: how many instances, and for how long

A scope says how many instances of a bean exist and how long each one lives:

ScopeInstancesTypical use
singleton (default)one per applicationservices, repositories, clients
prototypea new one every time it’s requestedobjects with their own state, builders
requestone per HTTP requestdata about the current request
sessionone per user sessionrarely needed in REST APIs

Singleton is the default for a reason: one OrderService can serve thousands of requests at once, as long as it keeps no per-request data in its fields. Everything that belongs to one request lives in method parameters and local variables.

Scope controls instance lifetime: singletons live as long as the context and are shared across threads; prototypes are created per lookup or injection and then forgotten by the container (no destruction callbacks); web scopes (request, session, application) are bound to the current request or session through thread-bound attributes. The catch is the mismatch between lifetimes: dependencies are injected once, when the consumer is created, so a shorter-lived bean injected into a singleton is frozen for the singleton’s life. Two fixes: look up the dependency when you need it (ObjectProvider<T>, @Lookup methods) or inject a scoped proxy (proxyMode = TARGET_CLASS, the default for @RequestScope and @SessionScope), which resolves the current target on every call. Web scopes also only exist on the request thread: code running in @Async methods, executors or reactive pipelines has no request to resolve against.

Predict the output

Cart is @Scope('prototype') and injected into the singleton CheckoutService. Two different customers each call addToCart once. How many items does the cart hold after the second call?

@Component
@Scope("prototype")
class Cart {
    val items = mutableListOf<String>()
}

@Service
class CheckoutService(private val cart: Cart) {
    fun addToCart(item: String) { cart.items += item }
}
@Component
@Scope("prototype")
class Cart {
    final List<String> items = new ArrayList<>();
}

@Service
class CheckoutService {
    private final Cart cart;
    CheckoutService(Cart cart) { this.cart = cart; }

    void addToCart(String item) { cart.items.add(item); }
}

A field that belongs to one request

Spot the bugUsers who see each other's discount

Tap the line with the bug.

@Service
class PricingService {
    private var currentCustomer: Customer? = null

    fun price(customer: Customer, product: Product): Money {
        currentCustomer = customer
        return product.price - discount(product)
    }

    private fun discount(product: Product): Money =
        if (currentCustomer!!.isPremium) product.price.percent(10) else Money.ZERO
}
@Service
public class PricingService {
    private Customer currentCustomer;

    public Money price(Customer customer, Product product) {
        this.currentCustomer = customer;
        return product.price().minus(discount(product));
    }

    private Money discount(Product product) {
        return currentCustomer.isPremium() ? product.price().percent(10) : Money.ZERO;
    }
}

Exerciseeasy

A fresh object per use

A ReportService (singleton) builds PDF reports with a ReportBuilder bean that collects rows in a list. ReportBuilder is @Scope("prototype"), yet reports contain rows from earlier reports. Fix it so every call to createReport gets a new builder, without making ReportService a prototype.

›

The builder is injected once. Ask the container for a new one each time you need it.

SolutionTry it yourself first
@Service
class ReportService(private val builders: ObjectProvider<ReportBuilder>) {
    fun createReport(rows: List<Row>): ByteArray {
        val builder = builders.getObject()              // a new prototype on every call
        rows.forEach(builder::add)
        return builder.toPdf()
    }
}
@Service
public class ReportService {
    private final ObjectProvider<ReportBuilder> builders;

    public ReportService(ObjectProvider<ReportBuilder> builders) {
        this.builders = builders;
    }

    public byte[] createReport(List<Row> rows) {
        ReportBuilder builder = builders.getObject();   // a new prototype on every call
        rows.forEach(builder::add);
        return builder.toPdf();
    }
}

ObjectProvider asks the container at the moment you call getObject(), so the prototype scope finally does what its name says. Often the simplest fix is even better: if ReportBuilder has no dependencies, don’t make it a bean and just write new ReportBuilder().

Request scope off the request thread

A @RequestScope bean injected into a singleton is a proxy; each call resolves the bean bound to the current thread’s request. Call it from an @Async method, a CompletableFuture on another executor, a scheduled job or a Kafka listener, and there is no request: the call fails with “Scope ‘request’ is not active for the current thread”. Pass the needed values (user id, locale, correlation id) as parameters, or propagate context explicitly (a TaskDecorator that copies it, Micrometer context propagation). The same reasoning applies to ThreadLocal-based state like SecurityContextHolder, which by default is per thread. With virtual threads, ThreadLocals still work but cost memory per thread; scoped values (finalized in Java 25) are the lighter replacement.

Deep divePrototype beans and destruction callbacksInterview favorite

The container creates a prototype, injects it, runs its init callbacks, and hands it over. From then on it keeps no reference: it doesn’t know when the object is no longer used, so @PreDestroy on a prototype bean never runs. A prototype that opens a connection or file leaks it unless the code that obtained it closes it.

If a short-lived object owns a resource, make it implement AutoCloseable and use it in try-with-resources (use in Kotlin), or give it a scope whose end the container does know (request scope, or a custom scope).

  • Singletons are shared across threads: no per-request state in fields.
  • Shorter-lived beans injected into singletons are frozen: use ObjectProvider<T>, @Lookup, or a scoped proxy (default for @RequestScope).
  • Web scopes only exist on the request thread; pass values to async work explicitly. Prototypes get no @PreDestroy.

Check this part

  1. How many instances of a @Service bean exist by default?

  2. A prototype-scoped bean is injected into a singleton's constructor. How often is a new instance created for it?

  3. An @Async method calls a @RequestScope bean. What happens?

  4. Does @PreDestroy run for prototype beans?

Beans are singletons by default: one instance shared by every request thread, so they must keep no per-request data in fields. Prototype beans are new per injection, so injecting one into a singleton happens only once; use ObjectProvider or a scoped proxy to get a fresh or current instance.

Part Not started

Proxies: where the annotations get their power

When you mark a method @Transactional, nobody adds code to your method. Spring creates a proxy, a subclass of your class generated at startup, and gives that to everyone who injects your bean. The proxy’s version of the method opens a transaction, calls your real method, and commits or rolls back:

  1. A controller calls orderService.placeOrder(). orderService is the proxy.
  2. The proxy starts a transaction and calls placeOrder() on your real object.
  3. Your code runs. When it returns, the proxy commits (or rolls back on an exception).

@Cacheable, @Async, @Retryable, @PreAuthorize and your own aspects all work the same way. And that’s where the classic bug comes from: a call that doesn’t go through the proxy skips all of it.

Spring AOP is proxy-based: advice (transactions, caching, security, async, custom @Aspects) is applied by a proxy that wraps the target bean. Spring Boot uses CGLIB subclass proxies by default (spring.aop.proxy-target-class=true); JDK dynamic proxies, which only implement interfaces, are used if you turn that off. Consequences: only calls that come through the proxy are advised, so self-invocation via this is not; private methods are never advised, and final methods can’t be overridden by a subclass proxy, so they run without advice and without any warning (since Spring 6, protected and package-private methods can be advised with class-based proxies). Kotlin classes and methods are final by default, which is why Spring projects use the kotlin-spring (all-open) compiler plugin. Workarounds for self-invocation: move the advised method to another bean (best), inject the bean into itself lazily, or use AspectJ weaving, which modifies the bytecode instead of wrapping it.

Predict the output

prices.loadPrice is @Cacheable. A controller calls priceWithTax('mug') twice. How many times does the slow database query in loadPrice run?

@Service
class PriceService {
    fun priceWithTax(sku: String): BigDecimal =
        loadPrice(sku) * BigDecimal("1.2")

    @Cacheable("prices")
    fun loadPrice(sku: String): BigDecimal = slowDatabaseQuery(sku)
}
@Service
public class PriceService {
    public BigDecimal priceWithTax(String sku) {
        return loadPrice(sku).multiply(new BigDecimal("1.2"));
    }

    @Cacheable("prices")
    public BigDecimal loadPrice(String sku) {
        return slowDatabaseQuery(sku);
    }
}

The annotation that is silently ignored

Spot the bugA transfer that half happens

Tap the line with the bug.

@Service
class TransferService {
    fun transfer(from: Long, to: Long, amount: BigDecimal) {
        moveMoney(from, to, amount)
    }

    @Transactional
    private fun moveMoney(from: Long, to: Long, amount: BigDecimal) {
        accounts.withdraw(from, amount)
        accounts.deposit(to, amount)       // throws if the target account is closed
    }
}
@Service
public class TransferService {
    public void transfer(long from, long to, BigDecimal amount) {
        moveMoney(from, to, amount);
    }

    @Transactional
    private void moveMoney(long from, long to, BigDecimal amount) {
        accounts.withdraw(from, amount);
        accounts.deposit(to, amount);      // throws if the target account is closed
    }
}

Your own aspect

The same mechanism is available to you. An aspect describes extra behavior (the advice) and where it applies (the pointcut); Spring builds the proxies:

@Aspect
@Component
class TimingAspect {
    private val log = LoggerFactory.getLogger(javaClass)

    @Around("@annotation(com.example.Timed)")
    fun time(call: ProceedingJoinPoint): Any? {
        val start = System.nanoTime()
        try {
            return call.proceed()                         // the real method
        } finally {
            log.info("{} took {} ms", call.signature.toShortString(),
                (System.nanoTime() - start) / 1_000_000)
        }
    }
}
@Aspect
@Component
class TimingAspect {
    private static final Logger log = LoggerFactory.getLogger(TimingAspect.class);

    @Around("@annotation(com.example.Timed)")
    Object time(ProceedingJoinPoint call) throws Throwable {
        long start = System.nanoTime();
        try {
            return call.proceed();                       // the real method
        } finally {
            log.info("{} took {} ms", call.getSignature().toShortString(),
                (System.nanoTime() - start) / 1_000_000);
        }
    }
}

It needs the spring-boot-starter-aspectj dependency (spring-boot-starter-aop before Spring Boot 4), and it has the same limits as @Transactional: only calls through the proxy, never self-calls or private methods. For timing in production, Micrometer’s @Timed and @Observed already do this.

Kotlin note

Kotlin classes and functions are final unless marked open, and a subclass proxy can’t override final methods. The kotlin("plugin.spring") Gradle plugin (added by start.spring.io) opens classes annotated with @Component, @Service, @Transactional, @Cacheable, @Async and a few others. Without it, the annotations are silently ignored.

Order of advice and proxy details

  • Several aspects on one bean are combined into one proxy; their order follows @Order (or Ordered). @Transactional and @Cacheable have configurable order too: with the cache outside the transaction, a cache hit opens no transaction at all.
  • @Async returns immediately with a CompletableFuture; exceptions from void async methods go to the AsyncUncaughtExceptionHandler, not to the caller. It runs on a TaskExecutor, so transactions, security context and request scope don’t travel with it.
  • @Transactional on an interface method works only with JDK proxies in older versions; put it on the implementation class.
  • The proxy is a different object: this inside the bean is the target, so passing this to another bean (listeners, callbacks) hands out the unproxied object. AopUtils.getTargetClass and AopUtils.isAopProxy help in diagnostics.
Deep diveJDK dynamic proxy or CGLIB?Interview favorite

A JDK dynamic proxy implements the bean’s interfaces and forwards calls through an InvocationHandler. It can only be injected by interface type: injecting OrderServiceImpl instead of OrderService fails with “bean is of type jdk.proxy2.$Proxy…”. A CGLIB proxy is a generated subclass of the bean’s class, so it can be injected by class and needs no interface, but it can’t override final classes or methods.

Spring Boot switched the default to CGLIB (proxy-target-class=true) in 2.0, precisely because “injected the implementation class and the app failed to start” was so common. Interviewers ask about it to see whether you know that “the annotation didn’t work” has a mechanical explanation: no proxy, or a call that bypassed it.

Exercisemedium

A company starter

Every service in your company copies the same setup: an AuditClient bean configured from properties, and an aspect that audits methods annotated with @Audited. Design a Spring Boot starter so that services get both by adding one dependency, can switch auditing off with a property, and can replace AuditClient with their own bean.

›

Auto-configuration classes are ordinary configuration classes with conditions, listed in a special file inside the starter’s jar.

SolutionTry it yourself first
@AutoConfiguration
@ConditionalOnClass(AuditClient::class)
@ConditionalOnProperty(prefix = "audit", name = ["enabled"], havingValue = "true", matchIfMissing = true)
@EnableConfigurationProperties(AuditProperties::class)
class AuditAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean                      // a service's own AuditClient wins
    fun auditClient(props: AuditProperties) = AuditClient(props.endpoint, props.timeout)

    @Bean
    fun auditAspect(client: AuditClient) = AuditAspect(client)
}

@ConfigurationProperties("audit")
data class AuditProperties(
    val endpoint: URI,
    @DefaultValue("2s") val timeout: Duration,
    @DefaultValue("true") val enabled: Boolean,
)
@AutoConfiguration
@ConditionalOnClass(AuditClient.class)
@ConditionalOnProperty(prefix = "audit", name = "enabled", havingValue = "true", matchIfMissing = true)
@EnableConfigurationProperties(AuditProperties.class)
public class AuditAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean                      // a service's own AuditClient wins
    AuditClient auditClient(AuditProperties props) {
        return new AuditClient(props.endpoint(), props.timeout());
    }

    @Bean
    AuditAspect auditAspect(AuditClient client) {
        return new AuditAspect(client);
    }
}

@ConfigurationProperties("audit")
record AuditProperties(URI endpoint, @DefaultValue("2s") Duration timeout, @DefaultValue("true") boolean enabled) {}

// src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
// com.example.audit.AuditAutoConfiguration

The design:

  • Registration through META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports, not component scanning: services don’t scan the starter’s packages, and auto-configurations are processed after the application’s own beans, which is what makes @ConditionalOnMissingBean reliable.
  • Back-off and switches: @ConditionalOnMissingBean lets a service provide its own client; audit.enabled=false removes everything; @ConditionalOnClass keeps the starter harmless if the client library is excluded.
  • Typed properties with defaults and validation, plus spring-boot-configuration-processor so IDEs autocomplete audit.*.
  • Tests with ApplicationContextRunner: assert the beans exist by default, disappear with audit.enabled=false, and back off when a user bean is present, without starting a whole application.
  • Ordering with @AutoConfiguration(after = …) if it depends on another auto-configuration’s beans.
  • Advice is applied by proxies: CGLIB subclasses by default in Boot. Only calls through the proxy are advised.
  • Self-invocation, private methods and final methods (Kotlin without the spring plugin) silently skip @Transactional, @Cacheable, @Async and custom aspects. Move the method to another bean.
  • @Async runs on another thread: no transaction, security context or request scope from the caller. Aspect order via @Order.
  • Starters: @AutoConfiguration listed in AutoConfiguration.imports, conditions to back off, @ConfigurationProperties, tested with ApplicationContextRunner.

Check this part

  1. Where does @Transactional's behavior come from at runtime?

  2. A public method calls a @Cacheable method of the same class. Is the cache used?

  3. Why do Spring projects in Kotlin use the kotlin-spring compiler plugin?

  4. What makes an auto-configuration step aside when the application defines its own bean?

@Transactional, @Cacheable, @Async and your own aspects work through proxies around the bean. A call from inside the same object goes through this, not through the proxy, so the annotation does nothing; so do private and final methods. Move the method to another bean, or call it through the proxy.

Key takeaways

  • Spring creates each bean, injects its dependencies, runs @PostConstruct, and may wrap it in a proxy; on shutdown it runs @PreDestroy.
  • Beans are singletons by default and shared by all requests: keep per-request data in parameters, never in fields.
  • A prototype injected into a singleton is created only once; use ObjectProvider when you need a new one each time.
  • @Transactional, @Cacheable and @Async work through proxies: calls from inside the same class, and private methods, skip them.
  • Know the lifecycle and its extension points: definitions and BeanFactoryPostProcessors, then instances, init callbacks and postProcessAfterInitialization, where proxies are made.
  • Scope mismatches freeze shorter-lived beans; web scopes and thread-locals don’t follow work to other threads.
  • Proxy limits (self-invocation, private and final methods, Kotlin’s final default) explain most “the annotation doesn’t work” bugs.
  • Starters are conditional auto-configurations that back off, registered in AutoConfiguration.imports and tested with ApplicationContextRunner.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.