What is Bean in Spring Boot? How to create a Bean?

Amar Balu
Javarevisited
Published in
7 min readMay 28, 2023

--

In Spring Boot, a bean is a Java object managed by the Spring framework’s IoC (Inversion of Control) container. It is a fundamental building block of a Spring application and represents a reusable component that can be wired together with other beans to create the application’s functionality.

Photo by Michiel Leunens on Unsplash

To create a bean in Spring Boot, you can follow these steps:

1. Define a Java class: Create a regular Java class that you want to manage as a bean.

2. Annotate the class: Use Spring’s annotations to indicate that the class should be treated as a bean. Common annotations include `@Component`, `@Service`, `@Repository`, or `@Controller`. These annotations provide additional functionality specific to their respective roles.

3. Configure component scanning: In your Spring Boot configuration file (typically annotated with `@SpringBootApplication`), enable component scanning to allow the Spring framework to automatically detect and manage your beans. You can do this by using `@ComponentScan` or `@SpringBootApplication` with appropriate package names.

4. Optionally, define dependencies: If your bean requires other beans, you can use dependency injection to inject those dependencies. You can use annotations like `@Autowired`, `@Resource`, or constructor injection to specify…

--

--

Amar Balu
Javarevisited

I'm a front-end developer. I love React and Redux, Java, and Data Science. I write code for fun!. Join our publication : https://medium.com/thefreshwrites