Sub topic 7
Defining beans with @Configuration and @Bean
This chapter assumes you know what a bean is and how constructor injection works. It also assumes you have used annotations such as @Service and @Component. Here you will register beans by writing Java methods instead of annotating classes.
When to use Java configuration
Component scanning needs you to put an annotation on the class. That is not possible when the class belongs to a library, such as a DataSource or an ObjectMapper. Java configuration is also useful when construction needs logic, such as choosing an implementation or setting several properties.
A class annotated with @Configuration holds bean definitions. Each method annotated with @Bean tells Spring: "call this method once, and keep the returned object as a bean."
A first configuration class
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@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);
}
}This code uses the MessageSender interface and the NotificationService class from the earlier chapters. Three rules explain how it works:
- The bean name is the method name by default. These beans are called
emailSenderandnotificationService. You can override the name with@Bean("customName"). - The bean type is the method's return type. Declare the interface, not the implementation, if you want callers to depend on the interface.
- Method parameters are injected from the container.
notificationServicereceives theMessageSenderbean without you callingemailSender()yourself.
Starting the container
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");
}
}
}Creating the context calls every @Bean method for singleton beans. Closing it at the end of the try block destroys them.
Calling one @Bean method from another
You can also wire beans by calling the other method directly:
@Bean
public NotificationService notificationService() {
return new NotificationService(emailSender());
}This works because Spring wraps @Configuration classes in a proxy subclass (a generated subclass that intercepts method calls). When you call emailSender(), the proxy checks the container first and returns the existing singleton. Without the proxy you would get a new object on every call.
Common errors
| Symptom | Likely cause |
|---|---|
| `NoSuchBeanDefinitionException` for your type | The configuration class is not registered with the context, or the method returns a different type than the one requested |
| `NoUniqueBeanDefinitionException` | Two `@Bean` methods return the same type. Use `@Primary` or `@Qualifier` |
| Two instances where you expected one | A direct `@Bean` method call in a class without the proxy |
| A bean is `null` in a `@Bean` method | The method returned `null`. Spring registers a null bean only in limited cases, so return a real object |
Mixing with component scanning
You can use both styles in one application. Scanning suits your own classes. @Bean methods suit third-party types and objects that need custom setup. If both define a bean with the same name, the later registration can override the earlier one, depending on your Spring Boot settings. Choose distinct names to avoid surprises.
Exercise
A configuration class has two methods. emailSender() is annotated with @Bean. notificationService() is annotated with @Bean and returns new NotificationService(emailSender()). The class is annotated with @Configuration. How many MessageSender instances exist, and why? What changes if you replace @Configuration with @Component?
Show answer
One instance exists. Spring proxies the @Configuration class, so the direct call to emailSender() returns the existing singleton from the container. With @Component, there is no proxy, so the direct call runs the method body again. This creates a second MessageSender, separate from the singleton bean.