Spring BootJava 21Spring Framework深入淺出

Spring Boot 02: who creates beans? Injection and auto-configuration

··5 min read
Back to the Spring Boot learning path

TicketController calls service.find without constructing a TicketService. Java does not invent the object: Spring supplies the dependency when it creates the controller. Find this construction path before treating annotations as magic.

Version note: this series is based on Spring Boot 3.5.16 because it targets JBoss EAP 8.1. Spring now offers the newer 4.1. For differences between 3.5 and 4.0, see the Spring Boot 4.0 Migration Guide in the sources.

A bean is a container-managed object

java
public TicketController(TicketService service, LabProperties properties) {
    this.service = service;
    this.properties = properties;
}

public TicketService(TicketStore store, LabProperties properties) {
    this.store = store;
    this.properties = properties;
}

These constructors come from the lab’s controller and service. They declare required collaborators and store them in final fields. Spring resolves the service’s own dependencies before supplying it to the controller; source-file order is not the construction algorithm. A single constructor here does not need @Autowired.

The top half shows three beans found by component scanning: TicketController, TicketService, and TicketStore, with arrows for constructor injection; the bottom half shows DataSource and JdbcClient from auto-configuration, connected to TicketStore; a side note says auto-configuration backs away when you define your own DataSource bean
Where the beans in this lab come from. Rules come from the Spring Framework 6.2 and Spring Boot 3.5 documentation; bean names come from the downloadable lab. Diagram drawn by KeepOnFirst.

Official rule: one constructor needs no annotation; several with no default constructor need one marked

The Spring Framework 6.2 documentation says that, as of 4.3, @Autowired on the constructor is no longer necessary if the target bean defines only one constructor. The next sentence gives the exception. With several constructors and no primary or default constructor, at least one must have @Autowired to tell the container which to use.

Constructors in the class@Autowired needed?In this lab
Only oneNo (since Framework 4.3)TicketController, TicketService
Several, no default constructorMark at least oneNone
Do you need @Autowired?

The documentation also gives a rule of thumb: use constructors for mandatory dependencies and setters or configuration methods for optional ones. The store and LabProperties are required here, so they are constructor arguments.

You can still construct ordinary objects with new. However, a manually created instance does not automatically receive Spring injection, lifecycle handling, or proxies just because its class has @Service. new Ticket is appropriate for a data value; manually constructing a service bypasses the transaction conditions used by this lab.

Four mechanisms to keep apart

MechanismRole in this labWhat it does not mean
StarterAdds related Maven dependenciesNot itself a running bean
Component scanFinds annotated application componentsDoes not scan every arbitrary package
@BeanRegisters an object through a configuration methodNot required for every application class
Auto-configurationApplies conditions based on libraries, configuration, existing beansDoes not infer business requirements
Ask whether it manages libraries or objects.

TicketStore is discovered by scanning. JdbcClient and DataSource are assembled when the relevant libraries and configuration satisfy their conditions. Some auto-configuration backs off when you define your own bean; inspect the specific conditions rather than assuming every default still applies, particularly with EAP-managed resources.

bash
java -jar target/boot-learning-lab-1.0.0.jar --debug

Start with --debug to inspect the condition evaluation report. Search for the data-source configuration and identify why conditions matched or failed. The report explains configuration decisions; it does not establish correct credentials, SQL behavior, or API compatibility.

The Boot 3.5 documentation states both points. First, auto-configuration is non-invasive: if you add your own DataSource bean, the default embedded database support backs away. Second, --debug enables debug logs for some core loggers and logs a conditions report to the console.

Backing away matters for migration. When the application moves to EAP and uses a JNDI datasource, your DataSource replaces the embedded database. After startup, find the DataSource entries in the conditions report to confirm which side applied.

Shared objects need appropriate state

A bean defaults to singleton scope within its container. A controller can handle concurrent requests, so request-specific users, inputs, or tickets do not belong in mutable instance fields. This lab stores stable collaborators and keeps ticket values local. Singleton scope neither means exactly one instance across the JVM nor guarantees thread safety.

The Bean scopes page describes the singleton as “per-container and per-bean”. This means one object for each Spring IoC container and each bean definition. With request scope, each HTTP request has its own object.

ScopeNumber of objectsIn this lab
singleton (default)One per Spring IoC containerController, service, store
requestOne per HTTP requestNot used
Two scopes compared (Spring Framework 6.2 Bean scopes page)

If one JVM creates two Spring containers, it holds two TicketService objects. That is what “per-container” means.

Exercise: remove one required bean

In a disposable copy, temporarily remove @Repository from TicketStore and run mvn package. Expect a missing TicketStore during test-context startup, not an HTTP 404. Restore the annotation and rerun the tests after reading the cause; skipping tests does not repair the wiring.

With a missing bean, the console again prints APPLICATION FAILED TO START, followed by Description and Action, the same box as in lesson 01. In the Boot 3.5 source, NoSuchBeanDefinitionFailureAnalyzer builds the text from the two format strings below. Each %s is filled in at runtime.

text
# Format strings from NoSuchBeanDefinitionFailureAnalyzer (Spring Boot 3.5.x branch).
# These are templates, not captured console output.
%s required %s that could not be found.
Consider %s %s in your configuration.

When a type is missing, the second %s is a bean of type 'FULL_TYPE_NAME'. In the action sentence, the first %s is defining when there are no candidates. When candidates exist but cannot be injected, it is revisiting the entries above or defining. The first %s of the description names the injection point; its wording was not checked, so it is not shown here.

From this format, the description in this exercise should contain the line below. Treat your own console as the source for the full text.

text
required a bean of type 'com.keeponfirst.bootlab.TicketStore' that could not be found

Answer and extension: what if there are two candidates?

A missing required dependency prevents construction; ambiguous candidates can also fail when selection rules do not resolve them. First determine why two candidates exist, then express intent through a qualifier or explicit configuration. Do not add @Primary merely to silence the error. Name the object and collaborator involved before changing wiring.

Download the complete ticket API lab (ZIP)Next: 03: Configuration and profiles

Sources