A bean in Spring Boot is a Java object that is under the IoC (Inversion of Control) container management of the Spring framework. It serves as a key building block for Spring applications and is a reusable part that can be combined with other beans to construct the functionality of the application.
You may do the following actions in Spring Boot to build a bean:
- Define a Java class: To manage as a bean, create a typical Java class.
- Annotate the class: To specify that the class ought to be handled as a bean, use Spring’s annotations. @Component, @Service, @Repository, or @Controller are examples of common annotations. Additional functionality relevant to their duties is provided by these annotations.
- Set up component scanning: To enable the Spring framework to automatically find and handle your beans, enable component scanning in your Spring Boot configuration file (usually annotated with
@SpringBootApplication). Using
@ComponentScan or `@SpringBootApplication with the proper package names will allow you to do this. - Define dependencies optionally. You may use dependency injection to inject dependencies if your bean needs other beans. To define the dependencies, you may use constructor injection or annotations such as @Autowired and @Resource.
This is an example of how to create a bean in Spring Boot:
import org.springframework.stereotype.Component;
@Component
public class MyBean {
// Bean implementation here
}
Regarding bean scopes, Spring offers many ways to manage bean visibility and lifespan. Although singleton is the default scope, you may define other scopes according to your needs:
- Singleton (default): When a bean is requested, Spring generates a single instance of the bean and returns it.
- Prototype: Whenever a bean is requested, Spring instantiates a new instance of it.
- Request: An HTTP request is the scope of the bean instance. Every request will have a unique bean instance.
- Session: An HTTP session is the scoped target for the bean instance. The bean will exist in separate instances for each session.
- Custom scopes: If the offered scopes are insufficient for your requirements, Spring additionally lets you create your own custom scopes.
The @Scope annotation may be used to define a bean’s scope. As an example, consider this:
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Scope("prototype")
public class MyBean {
// Bean implementation here
}
The MyBean
in this example will have a prototype scope, meaning that each time it is requested, a new instance will be produced.
In software development, the words “object” and “bean” have somewhat distinct connotations, especially when referring to the Spring framework.
What Distinguishes a Bean from an Object?
In programming, an object is a broad word that designates a specific instance of a class. It is a runtime object that contains both behaviour and data. Objects are the building blocks of object-oriented programming; their creation and manipulation are determined by the specifications of their classes.
Conversely, a bean is a notion exclusive to the Spring framework. An object under the control of the Spring IoC (Inversion of Control) container is called a bean in Spring. It is a Spring-configured and -controlled instance of a class. In a Spring application, beans are usually used to represent components and services.
The following are the main distinctions between beans and objects:
- Framework dependency: While beans are exclusive to the Spring framework, objects are a universal notion that may be utilised in any programming paradigm. The Spring container is in charge of managing and controlling beans.
- Configuration and lifecycle management: Using language elements like the
new
keyword, the developer directly creates and manages objects. Conversely, beans are generated and controlled by the Spring container. Bean scopes, dependency injection, and lifecycle callbacks are just a few of the lifecycle management tools that Spring offers for setting up and initialising beans. - Dependency injection: Beans specify their dependencies, and the Spring container injects those dependencies at runtime. This is a feature that Spring encourages the usage of. As a result, components may be loosely coupled. Generally speaking, objects may also have dependencies, but neither the language nor the framework supports maintaining or injecting such dependencies by default.
- Inversion of Control: Spring adheres to the Inversion of Control concept, which gives the container control over the creation and lifespan of objects. This frees the developer from having to directly manage object instantiation and wiring as the Spring container takes care of the creation, configuration, and maintenance of beans.
In conclusion, not all things are beans, even if all beans are objects. Within the Spring framework, beans are a distinct notion that stand in for objects that are controlled by the Spring container and provide extra functionality like dependency injection and lifecycle management.
In the Spring framework, a method that generates a bean is declared using the @Bean annotation. When you apply the @Bean annotation to a method, it tells the Spring container to use that method to create an instance of the bean and add it to the application context.
Why would you use @Bean Annotation?
What distinguishes @Bean from @Component, @Service, @Repository, and @Controller?
Although there is some functionality overlap, the stereotype annotations (@Component, @Service, @Repository, @Controller) and @Bean
in Spring are used for distinct reasons. @Bean and the stereotype annotations are contrasted here:
- Goal: – @Bean: In a configuration class, it is used to explicitly specify a bean object. The construction, setup, and startup of the bean are all under your precise control. – Stereotype Annotations (@Component, @Service, @Repository, @Controller): These annotations are used in the Spring container to auto-discover and register components with particular roles. They provide a practical means of classifying and distinguishing between various bean varieties.
- Configuration: – @Bean: It is used in a method or class that has an annotation with `@Configuration. The bean and all of its configuration parameters are clearly defined. – Stereotype Annotations: Usually, they don’t need a separate setup class; they may be used directly on classes. Beans marked with stereotype annotations are automatically detected and managed by the Spring container.
- Customisation: – You may provide your own custom logic for the creation and configuration of a bean by using
@Bean. The whole bean generation process is under your control; you may define the dependencies and provide unique initialization and destruction methods. - Stereotype Annotations: These provide a customisable means of designating a bean's function or role. For instance,
@Repository is often used for data access objects,@Controller for web controllers, and
@Service for business logic services. Certain traits and behaviour that are appropriate for their responsibilities are made possible by these annotations. - Scanning: @Bean: It doesn’t take part in the automated scanning of components. In a configuration class, the bean is defined directly. – Stereotype Annotations: When component scanning is enabled, the Spring container automatically finds and registers them. The classpath is searched for classes marked with stereotype annotations by the container, which then treats them as beans.
In actuality, the decision between stereotype and @Bean annotations is based on your unique needs. If you wish to explicitly declare beans in a configuration class or want fine-grained control over bean generation and configuration, use @Bean
. When beans fall into predetermined roles (e.g., service, repository, controller), use stereotype annotations to benefit from automated component scanning.
I hope this helps you understand what a bean is, how it differs from an object, and the many uses for beans.