Spring Java configuration: @Configuration classes and @Bean methods
Java configuration describes beans with ordinary methods: each @Bean method returns one object for the container to manage. Behind that simple model, Spring subclasses every @Configuration class so that calls between @Bean methods return shared beans. This page shows that mechanism running, the options on @Bean, splitting and switching configuration with @Import, @Profile and @Conditional, and the mistakes Spring rejects or silently tolerates.
Contents
How Java configuration works
A Spring container needs bean definitions: which objects to create, with which dependencies and settings. Java configuration writes them as code. A class marked @Configuration@Bean
The useful part is that a @Bean
One detail needs a mechanism. If two @Beanpool()@Configuration@Bean@Configuration(proxyBeanMethods = false)@Bean@Configuration
| Approach | Since | Best for |
|---|---|---|
XML <bean> | Spring 1.0 | Existing XML-based applications |
@Component | Spring 2.5 | Your own classes, one bean per class |
@Configuration@Bean | Spring 3.0 | Library classes, beans needing setup code, choices between implementations |
@Configuration(proxyBeanMethods = false) | Spring 5.2 | Configuration that injects through method parameters; faster startup |
GenericApplicationContext.registerBean | Spring 5.0 | Registration from code, without annotations |
Most applications mix the approaches: @Component@Configuration@Configuration
Full mode and lite mode
Three configurations declare the same connection pool and the data access objects that use it. A counter in the pool's constructor shows how many pools each one really creates:
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
public class FullVsLite {
static int pools = 0;
static class ConnectionPool {
final int id = ++pools;
}
record OrderDao(ConnectionPool pool) {
}
record CustomerDao(ConnectionPool pool) {
}
@Configuration
static class FullConfig {
@Bean
ConnectionPool pool() {
return new ConnectionPool();
}
@Bean
OrderDao orderDao() {
return new OrderDao(pool());
}
@Bean
CustomerDao customerDao() {
return new CustomerDao(pool());
}
}
@Configuration(proxyBeanMethods = false)
static class LiteConfig {
@Bean
ConnectionPool pool() {
return new ConnectionPool();
}
@Bean
OrderDao orderDao() {
return new OrderDao(pool()); // a plain Java call in lite mode
}
@Bean
CustomerDao customerDao(ConnectionPool pool) { // injected: always the bean
return new CustomerDao(pool);
}
}
@Component
static class BeansInAComponent {
@Bean
ConnectionPool pool() {
return new ConnectionPool();
}
@Bean
OrderDao orderDao() {
return new OrderDao(pool());
}
}
static void show(Class<?> config) {
pools = 0;
try (var context = new AnnotationConfigApplicationContext(config)) {
System.out.println(config.getSimpleName() + ":");
System.out.println(" config bean class: "
+ context.getBean(config).getClass().getSimpleName());
System.out.println(" pool bean id : " + context.getBean(ConnectionPool.class).id);
System.out.println(" OrderDao pool id : " + context.getBean(OrderDao.class).pool().id);
if (context.containsBean("customerDao")) {
System.out.println(" CustomerDao pool : "
+ context.getBean(CustomerDao.class).pool().id);
}
System.out.println(" pools created : " + pools);
}
}
public static void main(String[] args) {
show(FullConfig.class);
show(LiteConfig.class);
show(BeansInAComponent.class);
}
}
FullConfig:
config bean class: FullVsLite$FullConfig$$SpringCGLIB$$0
pool bean id : 1
OrderDao pool id : 1
CustomerDao pool : 1
pools created : 1
LiteConfig:
config bean class: LiteConfig
pool bean id : 1
OrderDao pool id : 2
CustomerDao pool : 1
pools created : 2
BeansInAComponent:
config bean class: BeansInAComponent
pool bean id : 1
OrderDao pool id : 2
pools created : 2
- In
, the configuration bean's class isFullConfig , the generated subclass. Both DAOs callFullVsLite$FullConfig$$SpringCGLIB$$0 , yet both got pool 1, and only 1 pool was created: the subclass returned the existing bean on each call.pool() - In
, the class is the plainLiteConfig .LiteConfig calledorderDao() as ordinary Java and got pool 2, a second pool that the container does not manage: nothing will close it, and no other bean shares it.pool() took the pool as a method parameter instead and got the real bean, pool 1.customerDao - In
, theBeansInAComponent methods are in a@Bean class, which is always lite mode, and the same duplicate pool 2 appeared.@Component
The safe pattern in every mode is to declare dependencies as @Bean@BeanproxyBeanMethods = false@AutoConfiguration
Options on @Bean methods
A @Bean
import java.util.Arrays;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Lazy;
public class BeanMethodOptions {
static class Named {
Named(String label) {
System.out.println(" creating " + label);
}
}
static class SchemaMigrator extends Named {
SchemaMigrator() {
super("SchemaMigrator");
}
}
static class ReportCache extends Named {
ReportCache() {
super("ReportCache (needs the migrated schema)");
}
}
static class PdfRenderer extends Named {
PdfRenderer() {
super("PdfRenderer (lazy)");
}
}
static class Clock extends Named {
Clock(String label) {
super(label);
}
}
record Scheduler(Clock clock) {
}
@Configuration
static class Config {
@Bean(name = {"mainClock", "systemClock"})
Clock clock() {
return new Clock("Clock (named mainClock, alias systemClock)");
}
@Bean(autowireCandidate = false)
Clock testClock() {
return new Clock("Clock (testClock, not a candidate for injection)");
}
@Bean
Scheduler scheduler(Clock clock) { // two Clock beans, but only one candidate
return new Scheduler(clock);
}
@Bean
@DependsOn("schemaMigrator")
ReportCache reportCache() {
return new ReportCache();
}
@Bean
SchemaMigrator schemaMigrator() {
return new SchemaMigrator();
}
@Bean
@Lazy
PdfRenderer pdfRenderer() {
return new PdfRenderer();
}
}
public static void main(String[] args) {
System.out.println("refresh():");
var context = new AnnotationConfigApplicationContext(Config.class);
System.out.println("after startup:");
System.out.println(" aliases of mainClock: "
+ Arrays.toString(context.getAliases("mainClock")));
System.out.println(" systemClock is mainClock: "
+ (context.getBean("systemClock") == context.getBean("mainClock")));
System.out.println(" scheduler got mainClock: "
+ (context.getBean(Scheduler.class).clock() == context.getBean("mainClock")));
System.out.println("asking for the PdfRenderer:");
context.getBean(PdfRenderer.class);
context.close();
}
}
refresh():
creating Clock (named mainClock, alias systemClock)
creating Clock (testClock, not a candidate for injection)
creating SchemaMigrator
creating ReportCache (needs the migrated schema)
after startup:
aliases of mainClock: [systemClock]
systemClock is mainClock: true
scheduler got mainClock: true
asking for the PdfRenderer:
creating PdfRenderer (lazy)
replaced the default name,@Bean(name = {"mainClock", "systemClock"}) , withclock , and addedmainClock as an alias. Both names return the same object.systemClock- There are two
beans, yetClock started without an ambiguity error and gotscheduler(Clock clock) .mainClock keepsautowireCandidate = false out of injection by type, while it can still be fetched by name.testClock was created beforeSchemaMigrator , although it is declared after it.ReportCache forces that order for a dependency that is not a constructor or method parameter, such as a migration that must finish first.@DependsOn("schemaMigrator") isPdfRenderer : it was not created during@Lazy , only whenrefresh() asked for it.getBean
Other annotations work on @Bean@Scope@Primary@Fallback@Qualifier@OrderinitMethoddestroyMethodclose()
Splitting configuration: @Import and ImportSelector
A real application has many configuration classes, usually one per area: data access, messaging, security. @ImportImportSelector@EnableTransactionManagement@EnableAuditing
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata;
public class ModularConfig {
record DataSource(String url) {
}
record OrderRepository(DataSource dataSource) {
}
record AuditLog(String target) {
}
@Configuration
static class DataConfig {
@Bean
DataSource dataSource() {
return new DataSource("jdbc:h2:mem:orders");
}
}
@Configuration
static class RepositoryConfig {
@Bean
OrderRepository orderRepository(DataSource dataSource) { // from another class
return new OrderRepository(dataSource);
}
}
@Configuration
static class FileAuditConfig {
@Bean
AuditLog auditLog() {
return new AuditLog("file");
}
}
@Configuration
static class DatabaseAuditConfig {
@Bean
AuditLog auditLog() {
return new AuditLog("database");
}
}
static class AuditSelector implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata metadata) {
Object target = metadata.getAnnotationAttributes(EnableAuditing.class.getName())
.get("target");
Class<?> chosen = "database".equals(target)
? DatabaseAuditConfig.class : FileAuditConfig.class;
System.out.println(" AuditSelector chose " + chosen.getSimpleName());
return new String[] {chosen.getName()};
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Import(AuditSelector.class)
@interface EnableAuditing {
String target() default "file";
}
@Configuration
@Import({DataConfig.class, RepositoryConfig.class})
@EnableAuditing(target = "database")
static class AppConfig {
}
public static void main(String[] args) {
System.out.println("Starting with AppConfig only:");
try (var context = new AnnotationConfigApplicationContext(AppConfig.class)) {
System.out.println(" " + context.getBean(OrderRepository.class));
System.out.println(" " + context.getBean(AuditLog.class));
System.out.println(" configuration classes registered: "
+ context.getBeanNamesForAnnotation(Configuration.class).length);
}
}
}
Starting with AppConfig only:
AuditSelector chose DatabaseAuditConfig
OrderRepository[dataSource=DataSource[url=jdbc:h2:mem:orders]]
AuditLog[target=database]
configuration classes registered: 4
- The context was started with
only, and 4 configuration classes ended up registered:AppConfig , the two it imports, and the one the selector chose.AppConfig received theOrderRepository declared in another class,DataSource . Beans from all imported classes form one pool of candidates, so aDataConfig method parameter can name a type defined anywhere.@Bean readAuditSelector from the annotation ontarget = "database" and choseAppConfig , so the audit log went to the database. Changing one attribute switches the whole module.DatabaseAuditConfig
Spring Boot's auto-configuration uses the same mechanism on a larger scale: an import selector loads the list of auto-configuration classes from META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports@ImportResource("classpath:legacy.xml")
Switching beans: @Profile, @Conditional and @Value
Configuration often depends on where the application runs. Here a development run should print mail instead of sending it, and a cache should exist only when a property switches it on. The program starts the same configuration twice, with different profiles and properties:
import java.util.Map;
import java.util.TreeMap;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.type.AnnotatedTypeMetadata;
public class ConditionalBeans {
interface MailSender {
String send(String to);
}
record Mailer(MailSender sender, String from, int retries) {
}
static class CacheEnabled implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return context.getEnvironment().getProperty("cache.enabled", Boolean.class, false);
}
}
record Cache(String name) {
}
@Configuration
static class Config {
@Bean
@Profile("dev")
MailSender consoleSender() {
return to -> "printed mail to " + to;
}
@Bean
@Profile("!dev")
MailSender smtpSender() {
return to -> "sent mail to " + to + " over SMTP";
}
@Bean
@Conditional(CacheEnabled.class)
Cache cache() {
return new Cache("orders");
}
@Bean
Mailer mailer(MailSender sender, @Value("${mail.from}") String from,
@Value("${mail.retries:3}") int retries) {
return new Mailer(sender, from, retries);
}
}
static void start(String profile, Map<String, Object> properties) {
var context = new AnnotationConfigApplicationContext();
context.getEnvironment().setActiveProfiles(profile);
context.getEnvironment().getPropertySources()
.addFirst(new MapPropertySource("app", properties));
context.register(Config.class);
context.refresh();
Mailer mailer = context.getBean(Mailer.class);
System.out.println("profile " + profile + ", properties "
+ new TreeMap<>(properties) + ":");
System.out.println(" " + mailer.sender().send("ana@example.com"));
System.out.println(" from " + mailer.from() + ", retries " + mailer.retries());
System.out.println(" cache bean present: " + context.containsBean("cache"));
context.close();
}
public static void main(String[] args) {
start("dev", Map.of("mail.from", "dev@localhost"));
start("prod", Map.of("mail.from", "shop@example.com", "mail.retries", "5",
"cache.enabled", "true"));
}
}
profile dev, properties {mail.from=dev@localhost}:
printed mail to ana@example.com
from dev@localhost, retries 3
cache bean present: false
profile prod, properties {cache.enabled=true, mail.from=shop@example.com, mail.retries=5}:
sent mail to ana@example.com over SMTP
from shop@example.com, retries 5
cache bean present: true
- With profile
, onlydev was registered, so the mail was printed. WithconsoleSender ,prod matched instead and the SMTP sender was used. Exactly one@Profile("!dev") existed in each run, soMailSender had no ambiguity.mailer injected the property from each run.@Value("${mail.from}") fell back to 3 when the property was missing, and Spring converted the text@Value("${mail.retries:3}") to the"5" 5 when it was present.int- The cache bean existed only in the second run, where
.cache.enabled=true is aCacheEnabled : Spring callsCondition before registering the bean, and skips the bean definition entirely when it returnsmatches .false
Conditions are evaluated while the definitions are read, before any bean exists. So a condition can look at the environment, the classpath and other definitions, but not at bean instances. @Profile@Conditional@ConditionalOnProperty@ConditionalOnClass@ConditionalOnMissingBeanCondition@PropertySource("classpath:app.properties")MapPropertySource
Mistakes Spring rejects, and one it tolerates
Because full mode works by subclassing, Spring checks the configuration classes at startup and refuses what it cannot subclass or override. One mistake passes that check and fails quietly instead. This program starts four configurations:
import java.util.logging.Level;
import java.util.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
public class ConfigTraps {
// hides the "cancelling refresh attempt" warning that repeats each failure below
static final Logger REFRESH_LOG = Logger.getLogger(
"org.springframework.context.annotation.AnnotationConfigApplicationContext");
record Region(String code) {
}
@Configuration
static final class FinalConfig {
@Bean
Region region() {
return new Region("eu");
}
}
@Configuration
static class PrivateBeanMethod {
@Bean
private Region region() {
return new Region("eu");
}
}
@Configuration
static class RegionConfig {
@Bean
Region region() {
return new Region("eu");
}
}
@Configuration
static class InstancePostProcessor {
@Autowired
Region region;
@Bean
BeanFactoryPostProcessor tweak() { // not static
return factory -> { };
}
@Bean
String greeting() {
return "region = " + region;
}
}
@Configuration
static class StaticPostProcessor {
@Autowired
Region region;
@Bean
static BeanFactoryPostProcessor tweak() {
return factory -> { };
}
@Bean
String greeting() {
return "region = " + region;
}
}
static void start(Class<?>... classes) {
System.out.println(classes[classes.length - 1].getSimpleName() + ":");
try (var context = new AnnotationConfigApplicationContext(classes)) {
System.out.println(" started, greeting bean: "
+ (context.containsBean("greeting") ? context.getBean("greeting") : "none"));
} catch (RuntimeException e) {
String message = e.getMessage();
System.out.println(" " + e.getClass().getSimpleName() + ":");
System.out.println(" " + message.substring(message.indexOf(':') + 2,
message.indexOf('\n')));
}
}
public static void main(String[] args) {
REFRESH_LOG.setLevel(Level.OFF);
start(FinalConfig.class);
start(PrivateBeanMethod.class);
start(RegionConfig.class, InstancePostProcessor.class);
start(RegionConfig.class, StaticPostProcessor.class);
}
}
FinalConfig:
BeanDefinitionParsingException:
@Configuration class 'ConfigTraps.FinalConfig' may not be final. Remove the final modifier to continue.
PrivateBeanMethod:
BeanDefinitionParsingException:
@Bean method 'region' must not be private or final; change the method's modifiers to continue.
InstancePostProcessor:
started, greeting bean: region = null
StaticPostProcessor:
started, greeting bean: region = Region[code=eu]
INFO:@Bean method InstancePostProcessor.tweak is non-static and returns an object assignable to Spring's BeanFactoryPostProcessor interface. This will result in a failure to process annotations such as @Autowired, @Resource, and @PostConstruct within the method's declaring @Configuration class. Add the 'static' modifier to this method to avoid these container lifecycle issues; see @Bean javadoc for complete details.
- A
configuration class failed withfinal :BeanDefinitionParsingException . CGLIB cannot subclass a final class. Records cannot bemay not be final classes in full mode for the same reason.@Configuration - A
private method failed with@Bean , because the subclass cannot override it. Both checks apply only to full mode; withmust not be private or final such classes are accepted.proxyBeanMethods = false started, but itsInstancePostProcessor field stayed empty:@Autowired . Itsregion = null method is not static, so Spring had to create the configuration class before the annotation processors existed. Spring logged anBeanFactoryPostProcessor message explaining this, the last line of the output, which goes to standard error.INFO- With the same method made
, the field was injected:static .region = Region[code=eu]
The rule for the last case: any @BeanBeanFactoryPostProcessorBeanPostProcessorPropertySourcesPlaceholderConfigurerstatic
Good habits with configuration classes
- Inject through parameters: write
instead of callingorderDao(ConnectionPool pool) . It works in both modes and shows the dependency in the method signature.pool() - Return the most specific type you want injected: until a bean is created, Spring knows its type only from the method's return type. A
bean whose method returns an interface cannot be found by its concrete class until something has created it.@Lazy - Keep configuration classes small: one class per area, combined with
, is easier to test and to switch with conditions than one class with every bean.@Import - Keep logic out of @Bean methods: building and configuring the object is fine; calling remote services or loading large data at startup belongs in a lifecycle callback or a runner.
Choosing how to declare a bean
| Situation | Use |
|---|---|
| Your own service, repository or controller | @Component@Service@Repository |
| A class from a library | A @Bean |
| A bean that needs setup code or a builder | A @Bean |
| Configuration classes that only inject through parameters | @Configuration(proxyBeanMethods = false) |
| One implementation per environment | @Profile@Bean |
| A bean that depends on a property or the classpath | @Conditional@ConditionalOn... |
| A module switched on with one annotation | An @Enable...@ImportImportSelector |
| A post-processor bean | A static@Bean |
The @Component