“Beans and Components in Java Spring: Simplified Explanation and Usage”

Zehra Gökçe Aynacı
5 min readAug 20, 2023

--

Have you ever wondered how Java Spring handles its magical behind-the-scenes work? If so, you’re in for a treat.

This article is a comprehensive guide to understanding what beans and components are, and how they power the inner workings of Spring.

Introduction:

In the realm of Java development, the Spring Framework stands as a powerful and widely used tool for building robust and scalable applications. Spring’s core concept are beans and components, which are crucial for achieving loose coupling, modularization, and efficient dependency management.

In this article, we will delve into the world of Beans and Components in Spring :

  • Understanding their significance
  • Exploring why they are used
  • Looking at some examples to solidify our understanding.

Before defining a Bean, it’s important to understand the concept of Inversion of Control (IoC). Inversion of Control (IoC) is a design principle (some people refer to it as a pattern) that focuses on inverting various forms of control within the object-oriented design, aiming to achieve loose coupling between components.

The key idea is that instead of a component creating its dependencies directly, the control is handed over to a container, which manages the creation and resolution of these dependencies.

You can find more detail and the difference between BeanFactory and ApplicationContext in detail in Spring by clicking here.

To better understand this concept, we can make a few more explanations as follows:

  • Let’s say you need to cook for your guest to come. This means that we control what food we cook. The IoC principle suggests inverting the control, which means we hire the chef and he does the cooking, instead of you doing the cooking. This time, the chef is in control of the food. You don’t have to cook yourself and you can let the chef do the cooking so that you can focus on your main work.

If something is dependent on a class, how do we use it →Dependency Injection

The process of creating classes that are Loosely Coupled

Dependency Injection(DI)

Dependency Injection is a fundamental aspect of the Spring framework, through which the Spring container “injects” objects into other objects or “dependencies”.

DI is the process of minimizing the dependency in the system by separating the parts that are coupling and giving them from the outside. This allows for loose coupling of components and moves the responsibility of managing components onto the container.

To summarize, by applying Dependency Injection, you can ensure that a class can act independently of the object it depends on, and you can eliminate the need to make changes despite possible improvements to the code.

“If you’re curious to learn more, you can check out the link here.”

Now let’s move to our main topic.

BEAN

A Bean in the Spring Framework is a Java object managed by the Spring IOC container. Beans are the fundamental building blocks of a Spring application and represent various components of the application, such as controllers, services, repositories, and more.

The working logic is like @Component. It assigns what it is defined to what we call Spring’s Application Context. If a method is defined with @Bean, it indicates that it produces a Bean managed by Spring.

When you use dependency injection and the concept of beans, you typically don’t need to manually create objects using the “new” keyword throughout your code. Instead, you define the structure and dependencies of your application's components in a configuration file or using annotations, and the container takes care of creating and wiring these objects for you.

Advantage Of Using Bean:

  • Modularity and Reusability
  • Dependency Injection
  • Configuration Management
  • Centralized Management
  • AOP Integration
  • Lifecycle Management
  • Scoping Options
  • Testing and Mocking

There are a number of ways you can create a Bean

  • Using Java base configuration
  • Using XML base configuration
  • Annotation-based configuration

In this article, we will focus on the Annotation-based configuration.

Let’s look at some code.

Domain Classes:

Traditional Approach:

Address address = new Address("Baker Street", "221B");
Company company = new Company(address);

There’s nothing wrong with this approach, but would it be advantageous to manage the dependencies in a more effective manner?

Imagine a program that contains dozens or even hundreds of classes. Sometimes we want to share a single instance of a class across the whole application, other times we need a separate object for each use case, and so on.

Declaring a Bean

Declaring a bean requires simply annotating a method with the @Bean annotation. The following is a simple example of a @Bean method declaration:

//First,let's decorate the Company class with the @Component annotation:
@Component
public class Company {
// this body is the same as before
}
@Configuration
public class Config {
@Bean
public Address getAddress() {
return new Address("Baker Street", "221B");
}
}

By default, the bean name will be the same as the method name.

Spring Stereotype Annotations

Spring can automatically detect our custom beans by using @Component annotation. So it is used to mark a Java class as a Spring bean.

  • @Component
  • @Service
  • @Autowired
  • @ComponentScan
  • @Controller
  • @Bean
  • @Configuration
  • @Required
  • @Repository, etc.
  • @Component is a class-level annotation whereas @Bean is a method-level annotation.
  • @Component is preferable for component scanning and automatic wiring.
  • The @Bean annotation returns an object that Spring should register as Bean in Application Context.
  • We cannot create a bean of a class using @Component if the class is outside Spring container whereas we can create a bean of a class using @Bean even if the class is present outside the Spring container.
  • @Component has different specializations like @Controller, @Repository and @Service whereas @Bean has no specializations.

Conclusion:

In summary, both @Component and @Bean are essential components of Spring's IoC and DI mechanisms. They provide flexibility in managing beans and their dependencies, catering to different use cases and levels of configuration control.

Finally, since it’s not possible to use @Component on classes because we don’t have the source code, we learned how to use the @Bean annotation instead.

Thanks for reading! Feel free to share your comments below.

--

--

Zehra Gökçe Aynacı

As a student, I chase excellence, committed to learning, embracing challenges and seeking guidance from experts.