Simple definition#
Spring learns which beans to create in three main ways:
- Component scanning: annotate your classes (
@Component,@Serviceand so on) and Spring finds them. - Java configuration:
@Beanfactory methods inside@Configurationclasses, ideal for third-party classes you cannot annotate. - Auto-configuration: Spring Boot’s conditional defaults. See auto-configuration.
The problem#
Without a clear configuration strategy, applications end up with duplicate beans, surprising overrides, beans scanned from the wrong packages, and environment-specific code paths scattered everywhere.
Component scanning and stereotypes#
@SpringBootApplication // = @SpringBootConfiguration + @EnableAutoConfiguration + @ComponentScan
public class ShopApplication { public static void main(String[] a) { SpringApplication.run(ShopApplication.class, a); } }
Scanning starts from the package of the annotated class and covers sub-packages. Put the main class in the root package.
| Annotation | Meaning | Extra behaviour |
|---|---|---|
@Component | Generic Spring-managed bean | — |
@Service | Business logic | None (it documents intent) |
@Repository | Data access | Exception translation to DataAccessException |
@Controller / @RestController | Web handlers | MVC mapping; @ResponseBody for REST |
@Configuration | Bean definitions | Proxied for inter-bean method calls |
Narrow scanning with @ComponentScan(basePackages = …, excludeFilters = …) only when needed. Scanning everything (com) slows startup and picks up surprises.
Java configuration with @Bean#
@Configuration
class PaymentConfig {
@Bean
RestClient paymentRestClient(RestClient.Builder builder, PaymentProperties props) { // dependencies as parameters
return builder.baseUrl(props.baseUrl())
.defaultHeader("X-Client", "shop")
.build();
}
@Bean
PaymentGateway paymentGateway(RestClient paymentRestClient) {
return new HttpPaymentGateway(paymentRestClient);
}
}
- The method name is the bean name (
paymentGateway). Override it with@Bean("name"). - Use
initMethodanddestroyMethodfor third-party lifecycle hooks. Spring infers publicclose()andshutdown()methods automatically. @Beanmethods can declare@Scope,@Lazy,@Primary,@Qualifier,@Orderand@Conditional*.
Full mode vs lite mode (proxyBeanMethods)#
@Configuration // proxyBeanMethods = true (full mode, the default)
class AppConfig {
@Bean Clock clock() { return Clock.systemUTC(); }
@Bean Scheduler scheduler() { return new Scheduler(clock()); } // returns the SAME singleton Clock
}
- Full mode: Spring subclasses the configuration class with CGLIB, so calling
clock()returns the container’s singleton. - Lite mode (
@Configuration(proxyBeanMethods = false)or@Beanin a@Component): no proxy, and callingclock()creates a new instance. Spring Boot’s own auto-configurations use lite mode for faster startup. Inject dependencies as method parameters instead of calling other@Beanmethods.
Composing configuration#
@Import(SecurityConfig.class)pulls in other configuration classes,ImportSelectors or registrars.- Enable-style annotations (
@EnableScheduling,@EnableCaching,@EnableAsync) are@Imports under the hood. - In Spring Boot, prefer auto-configuration for reusable modules (your own starters), so they back off when the application defines its own beans.
Profiles#
Profiles activate beans per environment:
@Configuration
@Profile("local")
class LocalStorageConfig { @Bean FileStore fileStore() { return new DiskFileStore(Path.of("/tmp/shop")); } }
@Configuration
@Profile("!local")
class CloudStorageConfig { @Bean FileStore fileStore(S3Client s3) { return new S3FileStore(s3); } }
- Activate them with
spring.profiles.active=prod, theSPRING_PROFILES_ACTIVEenvironment variable, or--spring.profiles.active. - Expressions:
@Profile("prod & !eu"),@Profile({"dev", "test"}). - Profile groups:
spring.profiles.group.prod=prod-db,prod-mq. - Keep profiles for wiring differences. Put values in externalized configuration, not in code branches.
Programmatic registration (Spring Framework 7)#
Spring 7 introduces BeanRegistrar, a flexible, AOT-friendly way to register beans in code. It is useful for registering a variable number of beans:
class ClientsRegistrar implements BeanRegistrar {
@Override
public void register(BeanRegistry registry, Environment env) {
for (String name : env.getProperty("shop.partners", String[].class, new String[0])) {
registry.registerBean(name + "Client", PartnerClient.class,
spec -> spec.supplier(ctx -> new PartnerClient(name)));
}
}
}
@Configuration
@Import(ClientsRegistrar.class)
class PartnerConfig { }
Organising configuration in large apps#
- One configuration class per concern (security, messaging, persistence, clients), next to the code it configures.
- Keep domain classes free of Spring annotations where practical. See hexagonal architecture.
- Bean overriding is disabled by default in Spring Boot (
spring.main.allow-bean-definition-overriding=false). Duplicate names fail fast; keep it that way.
Common mistakes#
Quick check#
What does @SpringBootApplication combine?
@SpringBootConfiguration (a @Configuration), @EnableAutoConfiguration and @ComponentScan from its package.
When use @Bean instead of @Component?
For third-party classes you cannot annotate, for objects that need construction logic, or to keep domain classes free of Spring annotations.
What does proxyBeanMethods = false change?
The configuration class is not CGLIB-proxied, so calling one @Bean method from another creates a new object. Inject dependencies as parameters instead.
What extra behaviour does @Repository add?
Translation of persistence exceptions into Spring’s DataAccessException hierarchy.
How do you activate a profile?
With spring.profiles.active in properties, an environment variable or a command-line argument. @Profile then selects beans.
Summary#
- Scan your own classes; use
@Beanfor third-party and complex construction. - Prefer method parameters to inter-bean calls; lite mode is faster.
- Use profiles for wiring differences and properties for values.
- Spring 7’s
BeanRegistrarhandles dynamic registration.
References#
- Spring Framework reference, Java-based Container Configuration.
- Spring Framework reference, Classpath Scanning and Managed Components.
- Spring Boot reference, Profiles.
- Spring Framework wiki, What’s New in Spring Framework 7.x.