Java Configuration

Basic Spring
≈ 2 min read

Container configuration with regular Java code

Not every bean is convenient to discover through Component Scanning. Sometimes a class comes from a third-party library, requires parameters during creation, or you need full control over which object goes into the container. For such cases, Spring supports Java Configuration.

@Configuration
class AppConfig {

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

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

A class marked with @Configuration contains configuration methods. A method marked with @Bean describes an object that Spring should register in the context. The returned value becomes a bean, and the method name is used as its default name.

The Clock clock parameter in the second method is a dependency. Spring finds a suitable bean and passes it when creating TokenService. This keeps configuration declarative: we describe the relationships, while the container determines the assembly order.

When to choose Java Configuration

  • you need to add an object of a class that you cannot annotate;
  • object creation requires explicit setup or a factory method;
  • you want infrastructure beans to be visible in one place.
Component Scanning and @Bean do not compete with each other. One application usually uses both approaches: your own services are convenient to discover automatically, while infrastructure objects are convenient to describe explicitly.