You are here
Home > java >

What is Bean in Spring

What is Bean in SpringEvery Java Developer come across the terms Java Bean, Bean Class & Spring Bean. Most of the times people think that all are the same and used interchangeably. Even sometimes people consider them as a simple POJO class. In fact, these all have some logical differences. There are some set of standards & guidelines provided by Programmers that make them different from each other. In this article ‘What is Bean in Spring?’, we will start with the fundamentals which are also essential to know, then we will discuss the Spring Bean with examples.

Please note that if you define a class that doesn’t follow the guidelines of being a Spring Bean, the Java compiler will never complain you. In contrast, the Spring Container will complain you that it is unable to find any Spring Bean at runtime. Hence, it is the programmer’s responsibility to mark a class as a Spring Bean so that the Spring Container can recognize it manage its life cycle accordingly. Let’s discuss our article ‘What is Bean in Spring?’, and its related concepts.

Before discussing ‘What is Bean in Spring?’, let’s understand ‘What is Bean Class or a Component Class?’

What is Bean Class/Component Class?

A bean is a Java class that contains state and behavior with a condition that state must be used in the business logic of the behavior. Programmatically, the non-static member variables represent the state of the class. On the other hand, methods represent the behavior of the class. It is always recommended to declare member variables as private and methods as public so that member variables can be accessed only through methods, but not directly. For example, Service classes, DAO classes etc. are considered as Bean classes or Component classes.

Bean and Component are the similar terms which are used interchangeably most of the times. Bean class is the Sun MicroSystem’s terminology, whereas Component is the Microsoft’s terminology.

What is the difference between Java Bean & Bean Class?

The difference between Java Bean & Bean class is that a Bean class contains business logic methods, whereas a Java bean is a simple class with state, behavior, getters, setters and it doesn’t contain business logic methods. This is the logical difference only and set of guidelines that a programmer should follow. However, the compiler will never complain that you are not following the guidelines in such cases as these guidelines/standards are not defined by the Java compiler.

What is Bean in Spring?

A Java class whose object is created and managed by the Spring Container is called a Spring Bean. Moreover, we can consider any class as a Spring Bean, except an abstract class and an interface. It can also be a POJO class, Java Bean class or any other class as well.

How to mark a class as a Bean in Spring?

After knowing ‘What is Bean in Spring?’, let’s discuss how to mark a Java class as a Bean in Spring.

In order to let Spring Container recognize a class as a Spring Bean, we need to mark that class either in the XML configuration file or by using annotations.

Using XML Configuration File

Use <bean> tag in the configuration file to mark a Java class as a Spring Bean. This configuration file provides instructions to the Spring Container to consider the class as a Spring Bean. Furthermore, Spring Container handles the whole life cycle of that Spring Bean such as loading of the spring bean class, creating objects of the spring bean class, managing object of the spring bean class, and destroying the spring bean class. For example, below code  represents that the Employee class is a Spring Bean.

<bean id="employee" class="com.dev.example.Employee"/>

Here, id becomes the object name for the Spring Bean internally. The class attribute must take the fully qualified class name.

Using Annotation

One of the other and the most popular way to mark a Java class as a Spring Bean is by using Annotations. When we apply @Component annotation in a Java class, it is considered as a Spring Bean by the Spring Container. However, there are many other annotations that can do the same job, but the @Component is the basic and the most widely used by the developers. For example, below Employee class is a Spring Bean.

@Component
public class Employee{
 . . . .
}

If we don’t specify any name, the class name with first letter in lower case will become the name of the Spring bean by default. In this case it will be ’employee’. However, we can provide the name of Spring Bean as @Component(“employee”).

We also have various Stereotype annotations that we can use as an alternative to @Component, but we should use them at some specific scenario. @Component is a class level annotation. Other stereotypes are a specialization of @Component. During the component scanning, Spring container automatically discovers the classes annotated with @Component, It registers them into the Application Context as a Spring Bean.

Using Java-based Configuration

There is one more way to mark a Java class as a Spring bean.

Since Spring 3.0, a pure-Java configuration container was provided. XML configuration is completely removed in this approach. The key features in Spring Framework’s new Java-configuration support are @Configuration annotated classes and @Bean annotated methods. Using @Configuration annotation at any Java class represents that Spring container will consider it as a source of Bean’s definitions. Using the @Bean tells the Spring container that method will return an object which should be registered as a Spring bean in the Spring container.

@Bean annotation plays the same role as the <bean/> element.

For example, below code demonstrates the concept of Java-based configuration:

@Configuration
public class EmployeeConfig{
   
   @Bean
   public Employee getEmployee(){
      return new Employee();
   }
}

As of now, we should have a clear understanding of ‘What is Bean in Spring?’. Let’s have a basic understanding of ‘How inheritance work in context of Bean in Spring?’.

How to configure inheritance in Spring Bean?

Generally, there are two approaches to configure inheritance in Spring Bean.

1) By using the ‘parent’ attribute in the @Bean annotation

2) In the XML configuration file by using ‘parent’ attribute.

Using @Bean annotation

Here’s how we can do it:

1) Define a parent bean configuration using the @Bean annotation in a configuration class as shown below:

@Configuration 
public class ParentConfig {
   
   @Bean 
   public ParentBean parentBean() {
    // return the bean instance 
   } 
}

2) Inherit from the parent bean configuration by defining another configuration class and using the @Bean annotation with the parent attribute.

@Configuration 
public class ChildConfig extends ParentConfig {
   
   @Bean(parent = "parentBean") 
   public ChildBean childBean() {
    // return the bean instance 
   } 
}

In the above example, ChildBean inherits from ParentBean, which is defined in the ParentConfig class.

Using XML configuration file

1) Define a parent bean configuration in the XML file as shown below:

<beans> 
   <bean id="parentBean" class="com.example.ParentBean"/>
</beans>

2) Inherit from the parent bean configuration by defining the child bean configuration and using the parent attribute.

<beans> 
   <bean id="childBean" class="com.example.ChildBean" parent="parentBean"/> 
</beans>

In the above example, ChildBean inherits from ParentBean, which is defined in the XML file.

When a bean is defined as a child bean, it inherits all the properties of the parent bean, including its dependencies, initialization, and destruction methods. However, we can also override or extend the properties of the parent bean in the child bean, if necessary.

Hope that this is enough to know ‘What is Bean in Spring?’, and its related concepts.

FAQ

Let’s talk about some FAQs to make your concept crystal clear on ‘What is Bean in Spring?’. It may help you in the interviews also.

Q1. Can we take a component class as a Bean in Spring?

Yes. Any class can be taken as a Bean in Spring, except abstract class and interface.

Q2. Can every component class be a Bean in Spring?

No, unless we mark it as a Bean in Spring.

Q3. Is every Java Bean class a Bean in Spring?

No, unless we mark it as a Bean in Spring.

Q4. Can an abstract class be a Bean in Spring?

No. Abstract class and interface can’t be a Bean in Spring.

Q5. Can a user defined non-POJO class be a Bean in Spring?

Yes. Any Java class, except interface & abstract class can be a Bean in Spring.

Q6. Does every POJO class implicitly become a Bean in Spring?

No, unless we mark it as a Bean in Spring.

Q7. What all Annotations can we use with a Bean in Spring?

There is a large list of annotations that we can use with a Bean in Spring. It’s not possible to explain each of them here. For that, kindly visit a separate article on ‘Spring Bean Annotations With Examples‘.

Q8. What is the difference between @Bean and @Component?

In Spring Framework, both @Bean and @Component annotations are used for creating beans. However, there are some technical differences between both of them:

1) We can apply @Bean to methods of a @Configuration annotated class that creates a bean, whereas @Component is used to annotate classes.

2) @Bean provides a lot of flexibility in configuring the bean, such as setting the scope, setting up dependencies, and initializing the bean, whereas @Component is a more general-purpose annotation and does not provide as much configuration flexibility.

Leave a Reply


Top