Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 66 ยท Inversion of Control and Beans

@Configuration and @Bean

Define Spring beans in Java with @Configuration and @Bean: bean names, dependencies as parameters, proxyBeanMethods, importing configs and third-party beans.

Annotating your own classes with @Component or @Service works when you own the source code. But many beans you need are not yours: a Clock, an ObjectMapper, an HTTP client from a library, a DataSource built from several settings. You cannot put an annotation on a class you do not control, and some objects need real code to build them. That is what Java configuration is for: a class annotated with @Configuration whose @Bean methods tell the container how to create each object.

In this lesson you will write @Bean methods, learn how the container names beans and wires them together through method parameters, understand the one famous option proxyBeanMethods, and see how configuration classes are combined. The real Spring code is read-only, because Spring cannot run on this site. The two runnable examples are plain-Java stand-ins that rebuild the mechanism in miniature, and each says what is real and what is imitation.

Two ways to declare a bean

@Component Annotate your own class. The scanner finds it.
@Bean Write a method that builds the object. Works for any class.

Use @Component for your code, @Bean for code you cannot annotate.

1 / 2

A first configuration class

Here is a small real configuration. It is read-only; nothing here runs on this page.

Java
import java.time.Clock;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class TimeConfig {

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

    @Bean
    TokenService tokenService(Clock clock) {
        return new TokenService(clock, 15);
    }
}

When the application starts, the container instantiates TimeConfig, then calls each @Bean method once and stores the results as singletons (see Bean Scopes and Lifecycle). Notice tokenService(Clock clock): the container sees a parameter of type Clock, finds the clock bean and passes it in. That is dependency injection with the method parameter as the injection point, so you never call clock() yourself.

A @Configuration class is itself a bean and is picked up by component scanning, because @Configuration is meta-annotated with @Component. In a Boot application the class marked @SpringBootApplication is also a configuration class, so you may put @Bean methods straight into it. For anything beyond a couple of beans, a separate configuration class keeps things tidy.

Bean names

Every bean has a name. For a @Bean method the default name is the method name, so the beans above are called clock and tokenService. You can choose another name, or several aliases:

Java
@Bean("smtpMailer")
Mailer mailer() { return new Mailer("smtp.example.org"); }

@Bean(name = { "mainDataSource", "primaryDataSource" })
DataSource dataSource() { ... }

The first name is the real name and the rest are aliases. Names matter when two beans share a type, which Qualifiers, @Primary and Collections covers. Two beans with the same name in the same context collide: by default Spring Boot refuses to let one silently override the other and fails the startup with a clear message.

Two practical rules:

  • The return type is the type the container registers. Declare the most useful type (often an interface), not a needlessly specific class.
  • @Bean methods may be package-private or protected, and they are usually not public. They are not an API, they are recipes.

Lifecycle hooks and third-party objects

Third-party classes cannot carry @PostConstruct. @Bean has attributes for that case:

Java
@Bean(initMethod = "start")
MessageClient client() { return new MessageClient("broker:5672"); }

For shutdown the container infers a public no-argument method named close or shutdown and calls it when the context closes, so most connection-like objects need nothing extra. Set destroyMethod = "" to turn that off.

Dependencies between @Bean methods

There are two ways one @Bean method can use another bean. The recommended one is the parameter, as you saw. The second is calling the other method directly:

Java
@Configuration
public class ShopConfig {

    @Bean
    Database database() {
        return new Database("jdbc:h2:mem:shop");
    }

    @Bean
    OrderRepository orderRepository() {
        return new OrderRepository(database());   // direct call
    }

    @Bean
    InvoiceRepository invoiceRepository() {
        return new InvoiceRepository(database()); // direct call
    }
}

Read that carefully. In plain Java, calling database() twice creates two Database objects. Yet Spring promises one singleton database bean. The reason both repositories still share one instance is that Spring does not use your class directly: it generates a subclass of ShopConfig at startup and overrides each @Bean method. The override first asks the container "do you already have the bean database?" and only runs your code the first time. This is called full mode, and it is the default.

The next TryIt rebuilds exactly that trick with an ordinary subclass, so you can see the difference between calling a method directly and calling it through a caching override.

Java Why direct @Bean calls need a caching subclass

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.

What is real: this is how full mode works, a generated subclass that intercepts @Bean methods (Spring uses a library to generate the subclass at runtime). What is the stand-in: we wrote the subclass by hand and cached in a map instead of asking a real container.

proxyBeanMethods

That subclass costs something at startup, and it only matters when @Bean methods call each other directly. So Spring lets you switch it off:

Java
@Configuration(proxyBeanMethods = false)
public class ShopConfig {

    @Bean
    Database database() { return new Database("jdbc:h2:mem:shop"); }

    @Bean
    OrderRepository orderRepository(Database database) {   // parameter, not a call
        return new OrderRepository(database);
    }
}

With proxyBeanMethods = false (called lite mode) no subclass is generated, startup is slightly faster and the class may even be final. The price is that direct calls between @Bean methods are ordinary Java calls and would create duplicates, so you must use parameters instead. Spring Boot's own auto-configuration classes all use proxyBeanMethods = false for that reason, and it is the style you should follow in your own code: inject by parameter, and switch proxying off. Keep the default only when you inherit code that relies on direct calls.

Building a mini bean factory

How does the container turn @Bean methods and their parameters into a working object graph? It reads each method's return type and parameter types, builds beans on demand and caches them. The stand-in below does that with a few lines of reflection and our own annotations (@MiniBean, @MiniConfiguration).

Java A mini @Bean factory

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 the creation order. Beans are visited alphabetically (clock, smtp, welcomeService), and welcomeService is last because it needs the other two. Had we asked for it first, the factory would have created its dependencies before it. The real container does the same, with far more features: scopes, aliases, post-processors, cycle detection and proxies. And the bean named smtp shows that a name given in the annotation replaces the method name.

Combining configuration classes

Large applications split configuration across several classes. There are three ways to bring them together.

  • Component scanning picks up every @Configuration class in the scanned packages automatically. In Boot this is the normal way for your own code.
  • @Import names classes explicitly: @Import({SecurityConfig.class, CacheConfig.class}). Use it for classes outside the scanned packages or to make dependencies between modules visible.
  • @ImportResource loads legacy XML bean definitions: @ImportResource("classpath:legacy-beans.xml"). You will rarely write it in new code.

Configuration classes can also inject beans from other configuration classes as method parameters, so there is no need for one class to know how another builds its object.

Prefer many small, focused configuration classes (WebConfig, JacksonConfig, ClientsConfig) over one giant one. Each can be tested and read on its own, and Boot's auto-configuration is organized exactly this way.

Static @Bean methods and a common warning

Some beans, such as BeanFactoryPostProcessor implementations, are needed very early, before the configuration class itself is ready. Declare those with a static @Bean method so the container does not have to instantiate the configuration class first. If you ever see a log warning that a configuration class "is not eligible for getting processed by all BeanPostProcessors", a non-static bean method of that kind is the usual cause.

@Bean or @Component?

Reach for @Component and its stereotypes (Component Scanning and Stereotypes) whenever the class is yours and needs no special construction. Use @Bean when you cannot annotate the class, when construction takes real logic (reading settings, choosing an implementation, calling a builder), or when you need the same class registered several times with different settings. Mixing both in one project is normal.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What name does the bean get when a method Clock clock() is annotated with a plain @Bean?

    The default bean name is the method name, so the bean is called clock. You can override it with @Bean("other").
  2. 2. In @Bean TokenService tokenService(Clock clock), where does the Clock argument come from?

    Parameters of a @Bean method are injection points. The container resolves each one by type (and name, if needed) before calling the method.
  3. 3. What does @Configuration(proxyBeanMethods = false) change?

    Lite mode skips the generated subclass. It starts a little faster, but a direct call such as database() would create a new object, so you must use method parameters for dependencies.
  4. 4. Which situation calls for @Bean rather than @Component?

    You cannot add an annotation to a third-party class, but a @Bean method can build and return an instance of it.

Summary

  • @Configuration classes hold @Bean methods; each method is a recipe whose return value becomes a bean.
  • The bean name defaults to the method name; @Bean("x") renames it and extra names are aliases.
  • Method parameters are injected by the container: that is the recommended way to wire beans together.
  • Full mode generates a subclass so direct calls between @Bean methods return the same singleton; proxyBeanMethods = false turns this off and is the modern default style.
  • Combine configuration with component scanning, @Import and (rarely) @ImportResource.
  • Use @Bean for third-party classes and non-trivial construction, @Component for your own classes.

Next: Bean Scopes and Lifecycle. For the framework view of the same topic, see Beans and Configuration in Spring.