Beans & IoC Container
A Spring bean is an object the ApplicationContext constructs, wires, and destroys.
Introduction
A Spring bean is an object the ApplicationContext constructs, wires, and destroys. OrderService does not choose when PricingClient is created. The context does, then hands the same singleton to every collaborator that asked for it.
Your types use stereotypes: @Component, @Service, @Repository, @Controller. Library types use a @Bean method — RestClient, Clock, an SDK you cannot annotate. Scan starts at OrdersApplication. @Repository also translates persistence exceptions. The default bean name of OrderService is orderService.
Scope defaults to singleton: one instance per context, safe when it is stateless. prototype is a new instance per lookup and is not destroyed for you. request and session exist only during HTTP. Injecting either into a singleton without ObjectProvider or proxyMode = TARGET_CLASS captures the first instance forever.
Boot auto-config often sets proxyBeanMethods = false. That lite mode skips a CGLIB subclass and starts faster; a direct call from one @Bean method to another can build a second object. Take collaborators as parameters. Full @Configuration intercepts those calls and returns the container singleton.
Purpose of this lesson
Register Orders beans, predict scope, and follow the lifecycle through the AOP proxy so a mutable field on a singleton is an obvious cross-customer leak.
Understanding the topic
The context is a name-to-instance map plus a lifecycle. Business code should not call getBean.
- Stereotype vs factory:
@Serviceon your class;@BeanforRestClientandClock. - Singleton: created at startup, cached, shared by every injection point.
- Proxy timing: after initialization, a
BeanPostProcessormay wrap the bean.@Transactionallives on that wrapper. - Close:
@PreDestroyruns for singletons. Prototypes are your responsibility.
Step-by-step explanation
- The context calls the constructor or
@Beanmethod and injects the remaining dependencies. @PostConstructruns, then post-processors may wrap the bean in a proxy.- The singleton is cached. External calls see
@Transactional;this.save()does not. - On shutdown the context destroys singletons. A prototype bean is not in that list.
Informative example
Library types are beans. RestClient (Spring 6.1 / Boot 3.2+) is the client to reach for; RestTemplate is in maintenance. Keys are placeholders. The next lesson replaces the two strings with a record. With proxyBeanMethods = false, pass dependencies as parameters.
@Configuration(proxyBeanMethods = false)public class OrdersInfraConfig {@BeanClock clock() { return Clock.systemUTC(); }@BeanRestClient stripeClient(@Value("${stripe.base-url}") String baseUrl,@Value("${stripe.api-key}") String apiKey) {return RestClient.builder().baseUrl(baseUrl).defaultHeader("Authorization", "Bearer " + apiKey).build();}}
Request scope inside a singleton needs proxyMode = TARGET_CLASS, or every call shares the first instance. Outside HTTP the scope is inactive.
Real-world use
TechLearningPro Orders registers OrderService with @Service, a UTC Clock, and a RestClient pointed at pricing. All three are singletons. Tests pass Clock.fixed. The audit id is request-scoped. Checkout never calls getBean; a missing collaborator fails the constructor before the first POST /api/orders. A class dropped in com.techlearningpro.common is not a bean until the scan includes it.
Security implications
Tomcat will share one mutable singleton across pooled threads. Scope mistakes become data leaks.
- Set
defaultHeaderonce, at build time. Mutating it per request attaches one customer's bearer token to the next call. Useclient.mutate(). Scope 'request' is not activemeans you are outside HTTP. Promoting a token holder to a singleton is the leak.- A forgotten
@Profile("prod")can leave a stub payment client on the live profile, or the live client on a laptop.
Best practices
- Keep singletons stateless. Pass the user id as a method argument.
- Build
RestClientandClockin configuration, and injectClock.systemUTC()in production. - Widen
scanBasePackagesonly for a module that truly lives outside the application package. - Prefer constructor parameters over
ApplicationContext.getBeanin domain code.
Common mistakes
- A
userIdor cart field on a@Service. The next request sees the previous customer. - A prototype injected once into a singleton. Look it up per call with
ObjectProvider<T>. - Calling another
@Beanmethod underproxyBeanMethods = falseand constructing a second client. @Componentabove the application package: startup succeeds, thenNoSuchBeanDefinitionException.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionWhat is the difference between a bean and an object you new?+
Answer
new skips transactions and configuration. @Service counts only when component scan sees the class. The default name of OrderService is orderService.2IntermediateQuestionWhen is @Bean the right registration?+
Answer
RestClient, Clock, an SDK. Pass other beans as method parameters, especially if proxyBeanMethods is false, so you do not accidentally construct a second instance.3AdvancedQuestionWhen does the transactional proxy appear, and what does it miss?+
Answer
@Transactional. Self-invocation does not. @PreDestroy runs for singletons on close, not for prototypes.Hands-on exercise
Lab. Publish @Bean Clock clock() as Clock.systemUTC(), stamp the order with clock.instant(), and test with Clock.fixed(Instant.parse("2026-01-15T00:00:00Z"), ZoneOffset.UTC). Delete any field that remembers the caller.
Summary
Orders is a context of singletons: the service, a Clock, a RestClient. Register the scope you mean, refuse shared mutable fields, and let constructors describe the graph.