@Configuration, @SpringBootApplication, @Bean, @Component

You will learn about @Configuration, @SpringBootApplication, @Bean, @Component, and a few more annotations in this lesson.

In our previous lesson, you learned about Spring Initializer, created the basic structure of the project, and added the necessary dependencies. In this lesson, let’s talk about the created files and a few annotations that Spring Boot provides.

What is Bean?

Bean is an instance of a Java object managed by a Spring IoC (Inversion of Control) container.

Inversion of Control is the process of being provided with objects along with their required dependencies without us creating them. The design pattern used for implementing an IoC is Dependency Injection, using which we can create and bind dependent objects.

Annotations

Annotation is a way of passing metadata about a field, class, method, constructor, etc., at compile time.

Spring offers various annotations to create and manage beans. Let’s look at a few of them.

@Scope

Scope of an object defines the region within which the object is accessible. All beans in Spring are by default SINGLETON. We can override the scope of the bean using @Scope("singleton").

Spring provides the following scopes:

Scope Description
singleton A single instance of the object created per Spring IoC
prototype new instance of the object created every time a request is made to the bean
request A new instance of the object is created for every single HTTP request, and the same will be used throughout the lifecycle of the HTTP request
session A new instance of the object is created and used throughout the lifecycle of every HTTP session
global session A new instance of the object is created and used throughout the lifecycle of the global HTTP session

Note: @Scope can be added for @Bean, @Component, @Service, @Controller, @RestController, etc.

The following code snippet demonstrates the usage of @Scope annotation.

Get hands-on with 1200+ tech skills courses.