Card 02/ 06

ExampleDifficulty: Beginner1 min

A Bean, Found by Scanning

@Component marks a class as one the container should create and manage. Pair it with @ComponentScan on a configuration class, and the container finds it by looking through the named package.

java
package rides;

@Component
class RideNotifier {
    void ping() { System.out.println("ready"); }
}

@Configuration
@ComponentScan(basePackages = "rides")
class AppConfig {}

public class ScanDemo {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        RideNotifier first = context.getBean(RideNotifier.class);
        RideNotifier second = context.getBean(RideNotifier.class);
        System.out.println("same instance: " + (first == second));
        first.ping();
    }
}
text
same instance: true
ready
run in a container, Spring Framework 6.1.14

Two calls to getBean(RideNotifier.class) return the same object — the container built exactly one RideNotifier and is handing that one out every time, which is what "managing its life" cashes out to for the simplest case.