Card 02/ 06

ExampleDifficulty: Beginner1 min

Spring Beans Example: A Bean Found by Component Scanning

One annotation on a class, one on a configuration class, and the container finds and creates it.

Component scanning is how the container, the part of Spring that creates and holds your objects, finds classes to turn into beans, the objects it creates and manages: it looks through a package for classes marked @Component and creates one of each. The listing marks RideNotifier as a component, points the scan at its package, and asks the container for it twice.

@Configuration marks AppConfig as a class that configures the container (the part of Spring that creates and holds the beans), and @ComponentScan names the package to search. AnnotationConfigApplicationContext starts a container from that configuration:

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

Both calls to getBean(RideNotifier.class) return the same object. The container created exactly one RideNotifier at startup and hands that one out every time; a single shared instance is what managing a bean's life means by default.

So marking a class @Component and scanning its package is enough for the container to create it, and to share one instance of it across the whole application unless you ask for something else.