Beans and dependency injection
This is the chapter that pays for the rest of the course. Almost every confusing Spring behaviour — silent nulls, ignored annotations, "expected single matching bean" — comes from something on this page.
What is a bean?
A bean is simply an object the Spring container created and manages. Not a special type, not an interface you implement — an ordinary Java object whose construction Spring took responsibility for.
You tell Spring about beans in two ways.
1 · Stereotype annotations (component scanning)
@Service
public class BookService {
private final BookRepository repository;
public BookService(BookRepository repository) {
this.repository = repository;
}
}
| Annotation | Meaning | Extra behaviour |
|---|---|---|
@Component | Generic managed object | None — the base annotation |
@Service | Business logic | None technically; pure documentation |
@Repository | Data access | Translates persistence exceptions into Spring's DataAccessException |
@Controller | Web controller returning view names | Discovered by handler mapping |
@RestController | @Controller + @ResponseBody | Return values serialised to the response body |
@Configuration | Class containing @Bean methods | Proxied so @Bean calls return the singleton |
2 · @Bean methods (explicit configuration)
Use this when you do not own the class — third-party types you cannot annotate.
@Configuration
public class HttpConfig {
@Bean
public RestClient inventoryClient(RestClient.Builder builder,
@Value("${inventory.base-url}") String baseUrl) {
return builder
.baseUrl(baseUrl)
.requestFactory(clientRequestFactory())
.build();
}
@Bean
ClientHttpRequestFactory clientRequestFactory() {
ClientHttpRequestFactorySettings settings = ClientHttpRequestFactorySettings.DEFAULTS
.withConnectTimeout(Duration.ofSeconds(2))
.withReadTimeout(Duration.ofSeconds(5));
return ClientHttpRequestFactories.get(settings);
}
}
The bean's name is the method name. Method parameters are themselves injected, which is how
inventoryClient receives the auto-configured RestClient.Builder.
Inside a @Configuration class, calling clientRequestFactory()
directly does not run the method again — Spring intercepts it and returns the
existing singleton. That is "full mode". On a plain @Component ("lite mode")
the call is a normal Java call and you get a second instance. This catches people out
when they refactor a @Configuration into something else.
Three ways to inject — and only one to use
@Service
public class BookService {
private final BookRepository repository;
private final ReviewClient reviews;
// @Autowired is optional on a single constructor since Spring 4.3
public BookService(BookRepository repository, ReviewClient reviews) {
this.repository = repository;
this.reviews = reviews;
}
}
Fields can be final, the object is never in a half-built state, and the
class is trivially testable with new. If the constructor grows to six
parameters, that is useful feedback about the class, not a reason to switch styles.
@Service
public class BookService {
@Autowired
private BookRepository repository; // not final, invisible dependency
}
Cannot be final; requires reflection or a Spring context to test;
hides how many dependencies a class really has; and allows circular dependencies to
exist quietly. Spring's own documentation recommends against it.
@Service
public class ReportService {
private ExportFormat format = ExportFormat.CSV; // has a sane default
@Autowired(required = false)
public void setFormat(ExportFormat format) {
this.format = format;
}
}
Reasonable for genuinely optional dependencies with a working default. Rare.
The bean lifecycle
@Component
public class ConnectionWarmer {
private final DataSource dataSource;
public ConnectionWarmer(DataSource dataSource) { // 1 · constructor
this.dataSource = dataSource;
}
@PostConstruct // 2 · after injection
void warmUp() throws SQLException {
try (Connection c = dataSource.getConnection()) {
c.isValid(1);
}
}
@PreDestroy // 3 · on context shutdown
void report() {
log.info("Shutting down cleanly");
}
}
Because beans are wrapped in proxies, calling an annotated method from inside the same class bypasses the annotation entirely. This compiles, runs, and silently does nothing:
@Service
public class OrderService {
public void placeOrder(Order order) {
this.saveWithTransaction(order); // ← plain Java call, NO proxy involved
}
@Transactional
public void saveWithTransaction(Order order) {
// there is no transaction here when called as above
}
}
The same applies to @Async, @Cacheable, @Retryable
and @PreAuthorize. Fix it by moving the annotated method to another bean, or
by injecting ApplicationContext and calling through the proxy.
When two beans match
Spring resolves by type first. Two implementations of one interface and it cannot choose:
Parameter 0 of constructor in com.bitsnippets.bookstore.catalog.BookService
required a single bean, but 2 were found:
- pdfExporter: defined in file [.../PdfExporter.class]
- csvExporter: defined in file [.../CsvExporter.class]
// 1 · @Primary — the default when nothing else is specified
@Component
@Primary
public class PdfExporter implements Exporter { }
// 2 · @Qualifier — ask for one by name
public ReportService(@Qualifier("csvExporter") Exporter exporter) { }
// 3 · a custom qualifier annotation — type-safe, refactor-friendly
@Qualifier("csv")
@Retention(RetentionPolicy.RUNTIME)
public @interface Csv { }
@Component @Csv
public class CsvExporter implements Exporter { }
public ReportService(@Csv Exporter exporter) { }
// 4 · take them all — Spring injects every implementation
@Service
public class ExportService {
private final Map<String, Exporter> exporters; // key = bean name
public ExportService(List<Exporter> all, Map<String, Exporter> byName) {
this.exporters = byName;
}
public byte[] export(String format, Report report) {
Exporter exporter = exporters.get(format + "Exporter");
if (exporter == null) {
throw new UnsupportedFormatException(format);
}
return exporter.export(report);
}
}
A strategy registry, a set of validators, a chain of enrichers — all become "add a class,
it is automatically picked up". Combine with @Order to control sequence,
and the List is injected in that order.
Bean scopes
| Scope | One instance per… | Use for |
|---|---|---|
singleton (default) | container | Almost everything. Must be stateless and thread-safe. |
prototype | injection point / getBean call | Stateful helpers. Note: the container never destroys these. |
request | HTTP request | Per-request context objects |
session | HTTP session | User-scoped state in stateful web apps |
application | ServletContext | Rare |
A singleton is created once, so a prototype or request bean
injected into it is also resolved once — and then frozen forever. Use a scoped proxy so
each call re-resolves:
@Component
@Scope(value = WebApplicationContext.SCOPE_REQUEST,
proxyMode = ScopedProxyMode.TARGET_CLASS)
public class RequestContext {
private String correlationId;
// getters and setters
}
Alternatively inject ObjectProvider<T> and call getObject()
when you need a fresh instance.
Optional and conditional beans
@Service
public class NotificationService {
private final Optional<SmsGateway> sms; // may be absent
private final ObjectProvider<AuditLogger> auditors; // lazy, 0..n
public NotificationService(Optional<SmsGateway> sms,
ObjectProvider<AuditLogger> auditors) {
this.sms = sms;
this.auditors = auditors;
}
public void notify(String phone, String message) {
sms.ifPresent(gateway -> gateway.send(phone, message));
auditors.ifAvailable(a -> a.record("sms", phone));
}
}
@Configuration
public class GatewayConfig {
@Bean
@ConditionalOnProperty(name = "sms.enabled", havingValue = "true")
SmsGateway twilioGateway(SmsProperties props) {
return new TwilioGateway(props.accountSid(), props.authToken());
}
@Bean
@ConditionalOnMissingBean(SmsGateway.class)
SmsGateway noopGateway() {
return (phone, message) -> log.info("SMS disabled, would have sent to {}", phone);
}
}
Circular dependencies
A needs B, B needs A. With constructor
injection this is impossible to satisfy, and since Boot 2.6 it fails the startup by design:
The dependencies of some of the beans in the application context form a cycle: ┌─────┐ | bookService defined in file [BookService.class] ↑ ↓ | reviewService defined in file [ReviewService.class] └─────┘
Ranked from best to worst:
- Extract the shared logicThe cycle almost always means a third concept is hiding inside one of the two classes. Pull it out into
C; both depend onC. - Use an application eventIf A merely needs to tell B that something happened, publish an event (chapter 13). The coupling disappears.
- Inject
ObjectProvider<B>Defers resolution until first use. Works, but the cycle is still there. @Lazyon one sideInjects a proxy that resolves on first call. Same caveat.spring.main.allow-circular-references=trueSilences the check. This is a migration aid, not a solution.
Inspecting the container
@Bean
ApplicationRunner listBeans(ApplicationContext ctx) {
return args -> Arrays.stream(ctx.getBeanDefinitionNames())
.sorted()
.filter(name -> name.startsWith("book"))
.forEach(System.out::println);
}
Actuator's /actuator/beans endpoint gives the same information as JSON,
including each bean's type, scope and dependencies — see
chapter 12.
Chapter checklist
- Constructor injection everywhere; fields
final; no@Autowiredon fields. - Main class in the root package so component scanning reaches everything.
- Singletons are stateless — any mutable field is a concurrency bug waiting to happen.
- Never call an annotated method on
thisand expect the annotation to apply. - Ambiguity resolved with
@Primaryfor the default and@Qualifierfor the exception. - A circular dependency is a design signal — fix the design first.
You add @Transactional to a private method. What happens?
Spring's default CGLIB proxies work by subclassing and overriding methods. Private (and final, and static) methods cannot be overridden, so the interception never happens. The annotation is silently ignored — which is exactly why this bug survives code review.