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 holds methods marked @Bean, and each method creates and returns one object. Spring calls the method once (for a singleton), keeps the result, and injects it wherever that type is needed. The method name becomes the bean name, and the method's parameters are dependencies that Spring resolves like constructor arguments.

The useful part is that a @Bean method is plain Java. It can call a library's builder, read a setting and branch on it, and the compiler checks every type and name. That makes it the natural way to register classes you did not write and cannot annotate, such as a connection pool, an HTTP client or a JSON mapper.

One detail needs a mechanism. If two @Bean methods both call pool() to get the connection pool, plain Java would create two pools. Spring avoids this by generating a CGLIB subclass of every @Configuration class at startup. The subclass overrides each @Bean method: the first call creates the bean, and later calls return the one already in the container. This is called full mode. With @Configuration(proxyBeanMethods = false), or @Bean methods in a class that is not a @Configuration, Spring uses lite mode: no subclass, and a call between methods is an ordinary call.

Ways to define beans
ApproachSinceBest for
XML <bean> definitionsSpring 1.0Existing XML-based applications
@Component classes found by scanningSpring 2.5Your own classes, one bean per class
@Configuration and @BeanSpring 3.0Library classes, beans needing setup code, choices between implementations
@Configuration(proxyBeanMethods = false)Spring 5.2Configuration that injects through method parameters; faster startup
GenericApplicationContext.registerBeanSpring 5.0Registration from code, without annotations

Most applications mix the approaches: @Component scanning for their own services, and @Configuration classes for infrastructure. Spring Boot's auto-configuration is itself a large set of @Configuration classes. All examples here are complete programs on Spring Framework 7.0 without Spring Boot.

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:

Java
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);
    }
}
Output
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 FullConfig, the configuration bean's class is FullVsLite$FullConfig$$SpringCGLIB$$0, the generated subclass. Both DAOs call pool(), yet both got pool 1, and only 1 pool was created: the subclass returned the existing bean on each call.
  • In LiteConfig, the class is the plain LiteConfig. orderDao() called pool() 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. customerDao took the pool as a method parameter instead and got the real bean, pool 1.
  • In BeansInAComponent, the @Bean methods are in a @Component class, which is always lite mode, and the same duplicate pool 2 appeared.

The safe pattern in every mode is to declare dependencies as @Bean method parameters rather than calling other @Bean methods. Then proxyBeanMethods = false is safe to use, which saves generating a subclass for each configuration class. Spring Boot's @AutoConfiguration classes are declared this way.

Options on @Bean methods

A @Bean method can set the bean's names, whether it may be injected, what it must wait for, and whether it is created at startup. This configuration uses each option once and prints when every bean is created:

Java
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();
    }
}
Output
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)
  • @Bean(name = {"mainClock", "systemClock"}) replaced the default name, clock, with mainClock, and added systemClock as an alias. Both names return the same object.
  • There are two Clock beans, yet scheduler(Clock clock) started without an ambiguity error and got mainClock. autowireCandidate = false keeps testClock out of injection by type, while it can still be fetched by name.
  • SchemaMigrator was created before ReportCache, although it is declared after it. @DependsOn("schemaMigrator") forces that order for a dependency that is not a constructor or method parameter, such as a migration that must finish first.
  • PdfRenderer is @Lazy: it was not created during refresh(), only when getBean asked for it.

Other annotations work on @Bean methods the same way they work on classes: @Scope, @Primary, @Fallback, @Qualifier and @Order. The initMethod and destroyMethod attributes, and the automatic close() they imply, are covered on the bean lifecycle page.

Splitting configuration: @Import and ImportSelector

A real application has many configuration classes, usually one per area: data access, messaging, security. @Import pulls other configuration classes in, so that starting the context with one root class brings in the rest. An ImportSelector chooses which classes to import at startup, and it is the mechanism behind annotations such as @EnableTransactionManagement. This program builds its own @EnableAuditing annotation on top of one:

Java
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);
        }
    }
}
Output
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 AppConfig only, and 4 configuration classes ended up registered: AppConfig, the two it imports, and the one the selector chose.
  • OrderRepository received the DataSource declared in another class, DataConfig. Beans from all imported classes form one pool of candidates, so a @Bean method parameter can name a type defined anywhere.
  • AuditSelector read target = "database" from the annotation on AppConfig and chose DatabaseAuditConfig, so the audit log went to the database. Changing one attribute switches the whole module.

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 files in each jar. @ImportResource("classpath:legacy.xml") imports an XML configuration in the same way, which helps when migrating from XML step by step.

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:

Java
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"));
    }
}
Output
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 dev, only consoleSender was registered, so the mail was printed. With prod, @Profile("!dev") matched instead and the SMTP sender was used. Exactly one MailSender existed in each run, so mailer had no ambiguity.
  • @Value("${mail.from}") injected the property from each run. @Value("${mail.retries:3}") fell back to 3 when the property was missing, and Spring converted the text "5" to the int 5 when it was present.
  • The cache bean existed only in the second run, where cache.enabled=true. CacheEnabled is a Condition: Spring calls matches before registering the bean, and skips the bean definition entirely when it returns 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 is itself a @Conditional. Spring Boot adds ready-made conditions such as @ConditionalOnProperty, @ConditionalOnClass and @ConditionalOnMissingBean, which replace most custom Condition classes. In a plain Spring application, @PropertySource("classpath:app.properties") on a configuration class adds a properties file to the environment, as the MapPropertySource does here.

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:

Java
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);
    }
}
Output
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 final configuration class failed with BeanDefinitionParsingException: may not be final. CGLIB cannot subclass a final class. Records cannot be @Configuration classes in full mode for the same reason.
  • A private @Bean method failed with must not be private or final, because the subclass cannot override it. Both checks apply only to full mode; with proxyBeanMethods = false such classes are accepted.
  • InstancePostProcessor started, but its @Autowired field stayed empty: region = null. Its BeanFactoryPostProcessor method is not static, so Spring had to create the configuration class before the annotation processors existed. Spring logged an INFO message explaining this, the last line of the output, which goes to standard error.
  • With the same method made static, the field was injected: region = Region[code=eu].

The rule for the last case: any @Bean method that returns a BeanFactoryPostProcessor or BeanPostProcessor, including PropertySourcesPlaceholderConfigurer, should be static. Spring can call a static method without creating the configuration object first. The failing runs also logged a "cancelling refresh attempt" warning each; the program turns that logger off to keep the output short.

Good habits with configuration classes

  • Inject through parameters: write orderDao(ConnectionPool pool) instead of calling pool(). It works in both modes and shows the dependency in the method signature.
  • 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 @Lazy bean whose method returns an interface cannot be found by its concrete class until something has created it.
  • Keep configuration classes small: one class per area, combined with @Import, is easier to test and to switch with conditions than one class with every bean.
  • 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

Which form to use
SituationUse
Your own service, repository or controller@Component (or @Service, @Repository) with constructor injection
A class from a libraryA @Bean method
A bean that needs setup code or a builderA @Bean method
Configuration classes that only inject through parameters@Configuration(proxyBeanMethods = false)
One implementation per environment@Profile on the @Bean methods
A bean that depends on a property or the classpath@Conditional, or Spring Boot's @ConditionalOn... annotations
A module switched on with one annotationAn @Enable... annotation with @Import or an ImportSelector
A post-processor beanA static @Bean method

The Spring annotations page covers @Component and scanning, the dependency injection page explains how parameters are resolved, and inversion of control shows how the container reads these definitions.