XML-based Spring configuration is verbose. Every bean declaration, property setting, and dependency wiring requires XML elements. As applications grow, XML files become unwieldy and hard to maintain. Developers need a more concise way to declare and configure beans directly in the code that defines them.
Spring annotations enable declarative bean definition and configuration directly in Java source code. Stereotype annotations (@Component, @Service, @Repository, @Controller) mark classes as Spring-managed beans. Configuration annotations (@Configuration, @Bean, @ComponentScan) replace XML configuration files with Java classes.
- Stereotype annotations:
@Component(generic),@Service(business logic),@Repository(data access),@Controller(web) — all register the class as a Spring bean - Annotation scanning:
@ComponentScantells Spring to scan specified packages for stereotype-annotated classes - Java configuration:
@Configurationclasses contain@Beanmethods that return objects to be managed as beans - Property injection:
@Value("${property.name}")injects values from properties files - Bean definition:
@Beanin@Configurationclass defines a bean with full lifecycle control - Conditional beans:
@Conditional,@Profilecreate beans only when specific conditions are met
- Stereotype hierarchy: @Service, @Repository, @Controller are specializations of @Component with different semantics
- Component scanning: Spring finds annotated classes via classpath scanning — no XML bean declarations needed
- Java config: @Configuration + @Bean replaces XML entirely with compile-time-checked config
- @Scope: Configures bean scope (singleton, prototype, request, etc.) on the bean class
- @Lazy: Defers bean initialization until first use instead of at container startup
- @Profile: Activates beans only in specific environments (dev, test, prod)
- Built from: Spring IoC Container — Annotations are a configuration method for the container
- Built from: Spring Framework — Annotations modernized Spring configuration
- Related: Spring Autowiring — @Autowired works alongside stereotype annotations
- Builds into: Spring MVC — @Controller, @RequestMapping are Spring MVC annotations
- Related: Spring Boot — @SpringBootApplication combines @Configuration + @ComponentScan + @EnableAutoConfiguration
- Annotation scan scope: Without @ComponentScan pointing to the right package, @Service and friends do nothing
- Ambiguous stereotypes: @Repository adds translation of persistence exceptions; @Service and @Component are functionally identical
- Proxy mode: Annotations on methods only work when called through the Spring proxy — internal method calls bypass them
- Annotation vs XML override: XML bean definitions can override annotation-based configurations if both are present