Card 01/ 06

ConceptDifficulty: Beginner1 min

Spring Beans: Objects the Container Creates and Manages

Whether an object is a bean depends on who made it, not on what it is.

A bean is an object that the Spring container created, supplied with its dependencies, and manages for the rest of its life. The container is the part of Spring that does this for every bean in an application, following the configuration you give it.

new RideNotifier() produces an object. It does not produce a bean, because your own code made it: the container never saw it, so it cannot hand it to anyone else or call it when the application shuts down.

That rules out two common assumptions. A bean is not any object a Spring-managed class happens to hold: a RideService bean can keep a HashMap it built itself, and the map is not a bean. And a bean is not defined by an annotation such as @Entity, which belongs to a different framework (JPA, for mapping objects to database tables). What makes an object a bean is who made it and who is looking after it.

In real code, the markers to look for are @Component on a class and a method annotated @Bean in a configuration class. Both tell the container to create an object, and the objects created that way are beans.

In a ride-sharing application, RideService, RideRepository and RideNotifier are typically beans: the container creates one of each at startup and passes the repository and the notifier into the service. The Ride objects those beans load and return are not beans. The service creates them many times a second, and the container never sees them.

So the question "is this a bean?" comes down to one question: did the container create this, or did my code? Only the container's objects get their dependencies injected and their lifecycle managed.