Skip to content
Tutorials Center
My learning

Topics

Lesson 59 of 119 ยท Spring Framework

Beans, Configuration and Component Scanning

Define Spring beans with @Component and @Bean, understand @Configuration proxies, scopes, lifecycle callbacks, @Primary and @Qualifier, and profiles, with runnable models.

In the previous lesson you built a container that creates objects and injects them into each other. Spring's container does the same, but it needs to know which objects to manage and how: which class to instantiate, whether to share one instance or create many, what to call after construction and before shutdown, and which candidate to pick when several fit. Each managed object is a bean, and the description of how to build it is a bean definition.

This lesson covers every everyday way to define beans: component scanning with stereotype annotations, @Configuration classes with @Bean methods, bean names, scopes, the lifecycle from constructor to @PreDestroy, choosing between candidates with @Primary and @Qualifier, and switching beans per environment with profiles. As before, Spring code is read-only here, and every mechanism also comes with a small runnable model that behaves the way Spring does.

Two ways to define beans

Component scanning and stereotypes

The most common way is to annotate your own classes and let Spring find them:

Java
@Service
public class InvoiceService {
    private final InvoiceRepository invoices;
    private final Clock clock;

    public InvoiceService(InvoiceRepository invoices, Clock clock) {
        this.invoices = invoices;
        this.clock = clock;
    }
}

@ComponentScan (included in Spring Boot's @SpringBootApplication) searches the package of the annotated class and all its subpackages for classes carrying @Component or an annotation that is itself annotated with @Component. These stereotypes all register a bean; they differ in what they communicate and in a few extras:

Annotation Use for Extra behavior
@Component any managed class none
@Service business logic none (pure documentation)
@Repository data access Spring translates persistence exceptions into its DataAccessException hierarchy
@Controller / @RestController web endpoints picked up by Spring MVC; @RestController adds @ResponseBody
@Configuration classes with @Bean methods proxied so @Bean methods return singletons (see below)

A class outside the scanned packages is silently ignored, which is the number one reason for "No qualifying bean" errors in new Spring Boot projects. Keep your main class in the root package (com.example.shop) and everything else below it.

@Configuration and @Bean

You can't put @Component on classes you don't own, like a connection pool, an ObjectMapper or java.time.Clock. And sometimes building an object needs logic or configuration values. For those cases, write a factory method annotated with @Bean in a @Configuration class:

Java
@Configuration
public class InfrastructureConfig {

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

    @Bean
    public DataSource dataSource(@Value("${app.db.url}") String url) {
        var config = new HikariConfig();
        config.setJdbcUrl(url);
        config.setMaximumPoolSize(10);
        return new HikariDataSource(config);   // closed automatically at shutdown
    }

    @Bean
    public InvoiceRepository invoiceRepository(DataSource dataSource) {
        return new JdbcInvoiceRepository(dataSource);
    }
}

The method's parameters are injected just like constructor parameters, and the return value becomes the bean. The bean name is the method name (clock, dataSource); for scanned components it is the simple class name with a lowercase first letter (invoiceService). You can override either: @Service("billing"), @Bean("primaryDataSource").

Use component scanning for your own application classes and @Bean methods for third-party objects and for anything that needs explicit construction logic. Both kinds of beans can depend on each other freely.

Why @Configuration classes are proxied

There is a subtle detail in @Configuration classes. Look at this version, where one @Bean method calls another directly:

Java
@Configuration
public class RepositoryConfig {
    @Bean DataSource dataSource() { return new HikariDataSource(...); }

    @Bean UserRepository userRepository()   { return new UserRepository(dataSource()); }
    @Bean OrderRepository orderRepository() { return new OrderRepository(dataSource()); }
}

In plain Java, dataSource() would run twice and create two connection pools. Spring prevents that by generating a subclass of every @Configuration class at startup (with the CGLIB library; you may see class names like RepositoryConfig$$SpringCGLIB$$0 in stack traces). The subclass overrides each @Bean method: if the bean already exists, it returns the existing instance instead of calling your code again. The model below writes that subclass by hand.

Java What the Configuration proxy does

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Without the proxy, three connection pools exist and the repositories don't even use the bean that the container manages. With it, there is exactly one. Two practical consequences follow:

  • @Configuration classes and their @Bean methods must not be final or private, because the proxy has to subclass and override them.
  • @Configuration(proxyBeanMethods = false) turns the proxy off ("lite mode"). It starts slightly faster and is what Spring Boot uses for its own auto-configuration, but then you must never call @Bean methods directly. Declare the dependency as a parameter instead, as invoiceRepository(DataSource dataSource) did above. That style works in both modes, so it is the one to prefer.

Bean scopes

A bean's scope decides how many instances exist and how long they live:

Scope Instances Typical use
singleton (default) one per container services, repositories, controllers, clients: almost everything
prototype a new one every time the bean is requested stateful helpers, builders
request one per HTTP request (web apps) request-specific context
session one per HTTP session a user's shopping cart, wizard state
application one per ServletContext rarely needed
Java
@Component
@Scope("prototype")         // or @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class ShoppingCart { ... }

@Component
@SessionScope               // shortcut for @Scope(value = "session", proxyMode = TARGET_CLASS)
public class UserPreferences { ... }

Because a singleton is shared by every thread that handles a request, singletons must be stateless or thread-safe. A field like private List<String> currentItems in a @Service is a bug waiting to happen: two users' requests will write into the same list. Keep per-request data in method parameters and local variables.

The prototype-in-singleton trap

Scopes interact in a way that catches many developers. A prototype bean injected into a singleton is created once, when the singleton is created, and then kept forever. The singleton never asks the container again.

Java A prototype injected into a singleton

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Ben's cart contains Ana's book, because "prototype" only mattered once. In Spring, you fix this by injecting an ObjectProvider<ShoppingCart> and calling getObject() whenever you need a fresh instance, by using a @Lookup method, or, for web scopes, with a scoped proxy (proxyMode = ScopedProxyMode.TARGET_CLASS, which @RequestScope and @SessionScope enable by default). The proxy is a singleton stand-in that forwards each call to the instance of the current request or session.

Custom scopes and the context hierarchy

The built-in scopes cover most needs, but the scope mechanism is open. A custom scope decides when the container creates a new instance and how long it lives. Spring ships SimpleThreadScope (one instance per thread) as an example, and teams write their own for things like "per tenant" or "per workflow run". You implement org.springframework.beans.factory.config.Scope:

Java
public class ThreadScope implements Scope {

    private final ThreadLocal<Map<String, Object>> beans = ThreadLocal.withInitial(HashMap::new);

    @Override
    public Object get(String name, ObjectFactory<?> objectFactory) {
        return beans.get().computeIfAbsent(name, n -> objectFactory.getObject());   // create on first use
    }

    @Override public Object remove(String name) { return beans.get().remove(name); }

    @Override public void registerDestructionCallback(String name, Runnable callback) { /* optional */ }
    @Override public Object resolveContextualObject(String key) { return null; }
    @Override public String getConversationId() { return Thread.currentThread().getName(); }
}

You then register it under a name. CustomScopeConfigurer is a BeanFactoryPostProcessor, so declare it as a static @Bean method, so that Spring can create it before the other beans:

Java
@Configuration
public class ScopeConfig {

    @Bean
    public static CustomScopeConfigurer customScopeConfigurer() {
        var configurer = new CustomScopeConfigurer();
        configurer.addScope("thread", new ThreadScope());
        return configurer;
    }
}

@Component
@Scope(value = "thread", proxyMode = ScopedProxyMode.TARGET_CLASS)   // proxy, because singletons will inject it
public class UserContext { /* per-thread state */ }

The proxyMode is the same trick you saw for request and session scope: a singleton that injects a narrower-scoped bean must receive a proxy that looks up the real instance on every call.

The context hierarchy

An ApplicationContext can have a parent. A child context sees all beans of its parent, but the parent knows nothing about its children, and a child may define a bean with the same name as one in the parent, which then overrides it for the child only. Classic Spring MVC applications without Boot use this on purpose: the root context holds services and repositories, and the servlet context of the DispatcherServlet is its child that holds controllers and view resolvers (the two config classes in Spring MVC are exactly that split). Spring Boot normally creates one single context, so the hierarchy matters mostly in older and in modular applications.

To see what a context contains, call context.getBeanDefinitionNames() (this lists only that context, not its ancestors), context.getBeanNamesForType(Service.class), or BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context, type) to include the parents. The program below models both ideas: a thread scope next to singleton and prototype, and two contexts, where the child asks its parent when it doesn't know a name. It is a plain-Java model, not the Spring classes.

Java A thread scope and a parent/child context

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Each thread got its own UserContext, and asking twice from the same thread gave the same instance: that is all a scope is. A bean name that uses a scope nobody registered fails with the same No Scope registered for scope name message that real Spring prints. In the hierarchy, web reaches userService through its parent, and its own greeting hides the parent's. root cannot see productController, because lookups only go upwards.

The bean lifecycle

Between "Spring decided to create this bean" and "the bean is ready", several steps run in a fixed order. At shutdown, a few more run in reverse:

  1. Instantiate: call the constructor (constructor injection happens here).
  2. Populate: setter and field injection.
  3. Aware callbacks: BeanNameAware, ApplicationContextAware and friends (rarely needed).
  4. BeanPostProcessor.postProcessBeforeInitialization for every registered post-processor.
  5. Initialization: @PostConstruct methods, then InitializingBean.afterPropertiesSet(), then a custom @Bean(initMethod = "...").
  6. BeanPostProcessor.postProcessAfterInitialization: this is where Spring wraps beans in AOP proxies for @Transactional, @Async or @Cacheable.
  7. The bean is ready and handed to whoever needs it.
  8. On shutdown: @PreDestroy, then DisposableBean.destroy(), then the destroyMethod. Beans are destroyed in the reverse order of creation, so dependents go first.

(Internally, @PostConstruct and @PreDestroy are themselves handled by a post-processor, CommonAnnotationBeanPostProcessor, but the order you observe is the one above.)

Java
@Component
public class ExchangeRateCache {
    private final RateClient client;
    private Map<String, BigDecimal> rates;

    public ExchangeRateCache(RateClient client) { this.client = client; }

    @PostConstruct                        // jakarta.annotation.PostConstruct
    void load() { rates = client.fetchAll(); }

    @PreDestroy                           // jakarta.annotation.PreDestroy
    void persist() { client.saveSnapshot(rates); }
}

Use @PostConstruct for work that needs all dependencies injected, such as warming a cache or validating configuration. Don't do that work in the constructor of a bean that uses field injection, because its fields are still null there. (With constructor injection everything is available in the constructor, which is another point in its favor.) For @Bean methods, Spring automatically calls a public close() or shutdown() method at shutdown, which is why the HikariDataSource above needs no extra configuration.

The model below runs these steps with its own @PostConstruct and @PreDestroy annotations and a logging post-processor.

Java The bean lifecycle step by step

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The output follows the list above exactly, and at shutdown PriceService is destroyed before the RateCache it depends on. One more rule that surprises people: Spring does not call destroy callbacks on prototype beans. The container hands them out and forgets them, so cleaning them up is your job.

Choosing between candidates: @Primary and @Qualifier

When exactly one bean matches a dependency's type, Spring injects it. When several match, it needs help, or startup fails with NoUniqueBeanDefinitionException. Spring decides in this order:

  1. @Qualifier on the injection point narrows the candidates to beans with that qualifier (or that bean name).
  2. If several remain, a bean marked @Primary wins.
  3. Otherwise, a bean whose name matches the parameter name wins. This needs the code to be compiled with -parameters, which Spring Boot's Maven and Gradle plugins configure for you.
  4. Otherwise, startup fails.
Java
@Component @Primary
class CardPaymentClient implements PaymentClient { ... }

@Component @Qualifier("invoice")
class InvoicePaymentClient implements PaymentClient { ... }

@Service
class CheckoutService {
    CheckoutService(PaymentClient payments,                               // CardPaymentClient (primary)
                    @Qualifier("invoice") PaymentClient businessPayments,  // InvoicePaymentClient
                    List<PaymentClient> all) { ... }                       // both
}

@Primary says "the default choice"; @Qualifier says "this specific one". Prefer @Primary for the common case and qualifiers for the exceptions. For many qualifiers, define your own annotation meta-annotated with @Qualifier (@Invoice) so typos become compile errors instead of startup errors.

Profiles and conditional beans

The same application needs different beans in different environments: a real SMTP mailer in production, one that just logs in development, an in-memory store in tests. Profiles switch bean definitions on and off:

Java
@Component
@Profile("prod")
class SmtpMailSender implements MailSender { ... }

@Component
@Profile("!prod")              // every profile except prod, including no profile
class LoggingMailSender implements MailSender { ... }

You activate profiles with spring.profiles.active=prod in configuration, the SPRING_PROFILES_ACTIVE environment variable or @ActiveProfiles("test") in tests. Beans without @Profile are always active. Spring Boot adds finer-grained conditions on top: @ConditionalOnProperty, @ConditionalOnClass and @ConditionalOnMissingBean, which is how auto-configuration backs off when you define your own bean. Configuration, Properties and Profiles covers profile-specific property files.

The next model implements the selection rules: profiles first, then qualifiers, then @Primary.

Java Resolving candidates with profiles, qualifiers and Primary

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice that a bean name works as a qualifier too (cardPaymentClient, jsonExporter), that !prod selects the logging mailer whenever production is not active, and that the two exporters without @Primary or a qualifier are ambiguous. A misspelled qualifier (xml) leaves no candidates at all. Spring reports both problems at startup, with the candidate names in the message.

A few more bean annotations

  • @Lazy: create the bean on first use instead of at startup. Useful for expensive, rarely used beans; it also delays wiring errors, so use it sparingly. Spring Boot can make everything lazy with spring.main.lazy-initialization=true, which speeds up startup in development.
  • @DependsOn("flywayInitializer"): force another bean to be created first when there is no injection relationship between them.
  • @Order / Ordered: order beans in an injected List, and order post-processors and filters.
  • @Value("${app.page-size:20}"): inject a configuration value, with a default after the colon.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Your @Service class lives in com.example.billing, but the @SpringBootApplication class is in com.example.shop. What happens?

    Component scanning covers the main class's package and its subpackages only. com.example.billing is a sibling, not a subpackage.
  2. 2. In a @Configuration class (default settings), userRepository() and orderRepository() both call dataSource(). How many DataSource objects are created?

    Spring subclasses @Configuration classes and intercepts @Bean methods so repeated calls return the singleton. With proxyBeanMethods = false you would get one per call.
  3. 3. A prototype-scoped ShoppingCart is injected through the constructor of a singleton controller. How many carts does the controller use over its lifetime?

    Injection happens once. To get a new prototype each time, inject ObjectProvider<ShoppingCart> and call getObject(), or use a scoped proxy for web scopes.
  4. 4. Two beans implement Exporter, neither has @Primary, and a constructor asks for @Qualifier("csvExporter") Exporter exporter. What is injected?

    A bean name works as a qualifier value, so the qualifier narrows the candidates to one bean.
  5. 5. In which lifecycle step does Spring usually wrap a bean in an AOP proxy for @Transactional?

    Proxies are created by a BeanPostProcessor after initialization, so @PostConstruct runs on the raw object and other beans receive the proxy.

Summary

  • A bean is an object managed by the Spring container; its bean definition says how to build it.
  • Component scanning registers classes annotated with @Component, @Service, @Repository or @Controller in the main class's package and below.
  • @Bean methods in @Configuration classes create third-party or custom-built beans; parameters are injected. Configuration classes are proxied so @Bean methods return singletons; prefer parameters over direct calls.
  • Scopes: singleton (default, must be thread-safe), prototype, and the web scopes request and session. Use ObjectProvider or scoped proxies when a shorter-lived bean is needed inside a singleton.
  • Lifecycle: constructor, injection, post-processors, @PostConstruct, proxying, ready, and @PreDestroy in reverse order at shutdown (not for prototypes).
  • Pick between candidates with @Qualifier (specific) and @Primary (default); inject List<T> to get all of them.
  • Profiles and Boot's @Conditional... annotations turn beans on or off per environment.
  • A custom Scope (registered with CustomScopeConfigurer) decides when a new instance is created; a child ApplicationContext sees its parent's beans, never the other way round.

Next: Spring Expression Language (SpEL) and @Value.