Sub topic 7
Defining beans with @Configuration and @Bean
This chapter assumes you know core Java (classes, interfaces, constructors, annotations) and have seen the ApplicationContext as the container that holds beans. You should also know that component scanning registers classes annotated with @Component or @Service. Here you will learn the second way to define beans: Java configuration.
Why Java configuration exists
Component scanning works only for classes you own. You cannot put @Component on a class from a library, such as a DataSource or an ObjectMapper. You also cannot use it when the construction of an object needs logic, such as choosing an implementation from a setting.
Java configuration solves both problems. You write a class annotated with @Configuration. Inside it, each method annotated with @Bean tells Spring: "call this method, and register the returned object as a bean."
| Need | Scanning (`@Component`) | Java config (`@Bean`) |
|---|---|---|
| Class is yours to edit | Works well | Works |
| Class comes from a library | Not possible | Works |
| Construction needs logic | Awkward | Natural |
| Where the wiring is visible | Spread across classes | One place |
A first configuration class
The example below reuses the MessageSender interface and NotificationService class from the earlier chapters. NotificationService here has no @Service annotation. It is registered only through the configuration class.
@Configuration
public class AppConfig {
@Bean
public MessageSender emailSender() {
return (to, body) -> System.out.println("email to " + to + ": " + body);
}
@Bean
public NotificationService notificationService(MessageSender sender) {
return new NotificationService(sender);
}
}Three rules explain what happens here.
- The bean name defaults to the method name. The first bean is called
emailSender, the secondnotificationService. You can override it with@Bean("customName"). - The bean type is the method's return type. Declare the most useful type, often an interface, because Spring uses the declared type when it matches candidates for injection.
- The method parameters are injected.
notificationServiceasks for aMessageSender, and Spring supplies theemailSenderbean. This is dependency injection applied to a factory method.
Starting the container from a configuration class
To start a container with no scanning, pass the configuration class to AnnotationConfigApplicationContext.
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
try (var ctx = new AnnotationConfigApplicationContext(AppConfig.class)) {
NotificationService service = ctx.getBean(NotificationService.class);
service.welcome("ana");
}
}
}The constructor call builds every singleton bean. Closing the context in try-with-resources destroys them. In Spring Boot you rarely write this code yourself, because SpringApplication.run creates the context and finds your configuration classes.
Spring reads the method signatures first and works out the order from the parameters. You do not have to declare the methods in dependency order.
Ways to express dependencies between @Bean methods
There are two ways for one @Bean method to use another bean.
Method parameters. This is the form used above. Spring resolves each parameter from the container using the same rules as any other injection point, including @Qualifier and @Primary.
Calling another @Bean method directly. This also works inside a @Configuration class:
@Configuration
public class DirectCallConfig {
@Bean
public MessageSender emailSender() {
return (to, body) -> System.out.println("email: " + body);
}
@Bean
public NotificationService notificationService() {
return new NotificationService(emailSender());
}
}This looks like a plain Java call that would create a second sender. It does not. Spring wraps @Configuration classes in a generated subclass (a CGLIB proxy). The proxy intercepts the call to emailSender(), sees that the bean already exists, and returns the existing singleton. Both styles give the same result for singletons.
Prefer parameters. They make the dependency visible in the signature, they work with qualifiers, and they do not rely on the proxy.
@Configuration versus "lite" mode
Spring treats @Bean methods differently depending on the class they sit in.
- In a class annotated with
@Configuration, the class is proxied. Calls between@Beanmethods return the container's bean. This is called full mode. - In a class annotated with
@Component, or in a class with no stereotype at all,@Beanmethods still register beans. But the class is not proxied. A direct call toemailSender()runs the method again and creates a new object. This is called lite mode.
If you want to keep a @Configuration class without proxying, set proxyBeanMethods = false:
@Configuration(proxyBeanMethods = false)
public class FastConfig {
@Bean
public MessageSender emailSender() {
return (to, body) -> System.out.println("email: " + body);
}
@Bean
public NotificationService notificationService(MessageSender sender) {
return new NotificationService(sender);
}
}This skips proxy generation, which speeds up startup slightly. It is only safe when no @Bean method calls another one directly. Spring Boot's own auto-configuration classes use this setting, and it is a safe default for your classes if you always use parameters.
Wrapping classes you do not own
The strongest use case for @Bean is a third-party type. Here is a java.time.Clock bean. A Clock is a JDK class, so you cannot annotate it.
import java.time.Clock;
@Configuration
public class TimeConfig {
@Bean
public Clock clock() {
return Clock.systemUTC();
}
}Any service can now take a Clock in its constructor. A test can pass Clock.fixed(...) instead, which makes time-dependent code deterministic. Wrapping hard-to-control objects like clocks and random generators in beans is a common design habit.
Mixing scanning and Java configuration
The two approaches work together in one application. A typical split:
- Your own services and repositories use
@Serviceand@Repository, found by scanning. - Infrastructure objects and library types use
@Beanmethods.
A configuration class is itself a bean, and @Configuration is meta-annotated with @Component. So a scan that covers the package of a configuration class will register it. You can also pull configuration classes together explicitly with @Import:
@Configuration
@Import({AppConfig.class, TimeConfig.class})
public class RootConfig {
}Customizing a @Bean
@Bean accepts a few attributes. The ones you meet most often are:
| Attribute | Purpose |
|---|---|
| `name` (or `value`) | One or more bean names, replacing the method name |
| `initMethod` | Name of a method to call after construction |
| `destroyMethod` | Name of a method to call on shutdown |
You can combine @Bean with other annotations on the same method, such as @Primary, @Scope("prototype"), @Profile, and @Lazy. Later chapters cover these.
For destruction, Spring has a convenient default. If the returned object has a public no-argument method called close or shutdown, Spring calls it automatically when the context closes. This is called inferred destroy method. Set destroyMethod = "" to turn it off, for example when the object is a shared resource that something else owns.
Common mistakes
- Returning
voidornullfrom a@Beanmethod. Avoidmethod is a startup error. Anullresult registers a null placeholder, and injection into a required parameter fails later. - Declaring
@Beanmethods asprivateorfinalin a@Configurationclass. The proxy subclass must override them. Spring reports an error at startup for these. - Using
staticfor ordinary beans. Astatic@Beanmethod is valid and is used for special infrastructure beans, such asBeanFactoryPostProcessor. For normal beans it skips the configuration instance and the proxy, which is rarely what you want. - Two beans with the same name. A later definition can silently replace an earlier one in some setups, and Spring Boot disables this by default and fails at startup. Pick distinct method names.
- Expecting
newcalls to be managed. An object you create withnewinside a@Beanmethod is managed only if it is the returned value. Anything else you instantiate inside is a normal Java object.
Summary of the working model
A @Configuration class is a bean factory written in Java. Each @Bean method is a recipe. Spring reads the recipes, orders them by their parameters, runs each once for singletons, and stores the results under the method names. Method parameters are injection points, and in a full-mode configuration class even direct calls between methods return the stored bean.
Exercise
A class DbConfig is annotated with @Component (not @Configuration). It has @Bean Pool pool() and @Bean Repo repo() { return new Repo(pool()); }. How many Pool objects exist, and how would you fix the design?
Show answer
Two Pool objects exist. The class runs in lite mode, so the call to pool() inside repo() is an ordinary Java call and builds a new Pool in addition to the bean. Fix it by changing the annotation to @Configuration, or better, by writing Repo repo(Pool pool) { return new Repo(pool); } so the container injects the existing bean.
Exercise
You need a Clock bean so tests can control time. Which one is correct for the production bean: @Bean Clock clock() { return Clock.systemUTC(); } in a @Configuration class, or @Component on Clock? Why?
Show answer
Use the @Bean method. Clock is a JDK class you cannot annotate, so scanning cannot register it. The @Bean method registers it, and tests can supply Clock.fixed(...) instead.