Card 02/ 06
All 6 cards
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.
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();
}
}same instance: true
readyTwo 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.