Search code examples
javaspringgrailsspring-bean

What in the world are Spring beans?


I am yet to find a high-level definition of Spring beans that I can understand. I see them referenced often in Grails documentation and books, but I think that understanding what they are would be beneficial. So

  1. What are Spring beans?
  2. How can they be used?
  3. Do they have something to do with Dependency Injection?

Solution

  • The Spring core technologies reference documentation describes what beans are.

    Per the Introduction to the Spring IoC Container and Beans section (where "IoC" means "inversion of control"):

    In Spring, the objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and managed by a Spring IoC container. Otherwise, a bean is simply one of many objects in your application. Beans, and the dependencies among them, are reflected in the configuration metadata used by a container.

    Beans and scope are described in the Bean Scopes section:

    When you create a bean definition, you create a recipe for creating actual instances of the class defined by that bean definition. The idea that a bean definition is a recipe is important, because it means that, as with a class, you can create many object instances from a single recipe.

    You can control not only the various dependencies and configuration values that are to be plugged into an object that is created from a particular bean definition but also control the scope of the objects created from a particular bean definition. This approach is powerful and flexible, because you can choose the scope of the objects you create through configuration instead of having to bake in the scope of an object at the Java class level. Beans can be defined to be deployed in one of a number of scopes.