Chapter 03

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.

⏱ 20 min readLevel: beginner → intermediateCore chapter

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)

catalog/BookService.java
@Service
public class BookService {

    private final BookRepository repository;

    public BookService(BookRepository repository) {
        this.repository = repository;
    }
}
AnnotationMeaningExtra behaviour
@ComponentGeneric managed objectNone — the base annotation
@ServiceBusiness logicNone technically; pure documentation
@RepositoryData accessTranslates persistence exceptions into Spring's DataAccessException
@ControllerWeb controller returning view namesDiscovered by handler mapping
@RestController@Controller + @ResponseBodyReturn values serialised to the response body
@ConfigurationClass containing @Bean methodsProxied 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.

common/HttpConfig.java
@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.

Why @Configuration classes are proxied

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

the 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.

avoid this
@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.

occasionally justified
@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

Six lifecycle stages: instantiate, populate, aware and post-processors, initialise, proxy wrapping, ready — plus destruction
Step 5 is the one that explains most "my annotation did nothing" bugs.
hooks, in the order they run
@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");
    }
}
The proxy trap — remember this one

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:

the error
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]
four ways out
// 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);
    }
}
Injecting a List is an underrated pattern

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

ScopeOne instance per…Use for
singleton (default)containerAlmost everything. Must be stateless and thread-safe.
prototypeinjection point / getBean callStateful helpers. Note: the container never destroys these.
requestHTTP requestPer-request context objects
sessionHTTP sessionUser-scoped state in stateful web apps
applicationServletContextRare
Injecting a short scope into a long one

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

handling "might not exist"
@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));
    }
}
defining beans conditionally
@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:

startup failure
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:

  1. 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 on C.
  2. Use an application eventIf A merely needs to tell B that something happened, publish an event (chapter 13). The coupling disappears.
  3. Inject ObjectProvider<B>Defers resolution until first use. Works, but the cycle is still there.
  4. @Lazy on one sideInjects a proxy that resolves on first call. Same caveat.
  5. spring.main.allow-circular-references=trueSilences the check. This is a migration aid, not a solution.

Inspecting the container

listing every bean
@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 @Autowired on 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 this and expect the annotation to apply.
  • Ambiguity resolved with @Primary for the default and @Qualifier for 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.