Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 what are Spring beans? How can they be used? Do they have something to do with Dependency Injection?

like image 728
grantmcconnaughey Avatar asked Jun 19 '13 14:06

grantmcconnaughey


People also ask

What are Spring beans?

Advertisements. 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 otherwise managed by a Spring IoC container.

How Spring beans are created?

Bean life cycle is managed by the spring container. When we run the program then, first of all, the spring container gets started. After that, the container creates the instance of a bean as per the request, and then dependencies are injected. And finally, the bean is destroyed when the spring container is closed.

How do you identify a Spring bean?

The first step of defining Spring Beans is by adding the right annotation — @Component or @Service or @Repository . However, Spring does not know about the bean unless it knows where to search for it. This part of “telling Spring where to search” is called a Component Scan.


1 Answers

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.

like image 187
Juned Ahsan Avatar answered Oct 02 '22 01:10

Juned Ahsan