Preparing for Java and Spring Boot Interview?

Join my Newsletter, its FREE

Wednesday, August 9, 2023

Difference between @Component @Bean and @Profile in Spring Framework

Hello guys, if you are thinking what is difference between @Component, @Bean, and @Profile annotation in Spring then you have come to the right place. Earlier, I have shared  difference between @Component, @Service, @Reposistory and @Controller annotations and in this article, I am going to answer another popular Spring interview question about difference between Component, Bean and Profile annotation. If you are working in Java then you may know that Spring is a popular Java framework that provides a variety of tools and features for developing robust and scalable applications. In Spring, you can use annotations to simplify the configuration of your application and to manage dependencies between components. @Bean@Component, and @Profile are three commonly used annotations in Spring that serve different purposes.

The @Bean is used to create and configure individual beans explicitly in a configuration class, @Component is used to mark a class as a Spring-managed component that is automatically detected during component scanning, and @Profile is used to specify the environment or configuration profile in which a bean is active.

Understanding the differences between these annotations and when to use each one can help you write cleaner, more organized code and make it easier to maintain and update your application. In this article, we will dive deeper into the differences between @Bean, @Component, and @Profile annotations and provide some examples of when to use each one.

Let’s understand each of them one by one

What is @Bean annotation in Spring Framework?


• Used to declare a single bean explicitly in a configuration class.

• The bean is created and managed by Spring's container.

• @Bean annotated method should return an object instance that Spring uses to register a bean.

• The method name is by default the name of the bean but can be overridden using the name attribute.

• @Bean is typically used for creating third-party or non-Spring components, such as instances of a JDBC DataSource, RestTemplate, or a custom component that doesn't fit into the typical stereotype of a @Service, @Repository, or @Controller.

@Bean is most commonly used in Java configuration classes but can also be used in XML configuration.



What is @Component annotation in Spring?


• Mark a class as a component that is handled by Spring.

• During component scanning, the class is immediately identified and registered in the application context as a bean.

• Any class may be annotated as a Spring-managed component using Component annotation.

• When defining domain objects like Customers, Orders, or Products using @Component.

• One can create utility classes StringUtils and DateUtils using @Component.




What is @Profile annotation  in Spring Framework?


• Used to indicate the configuration profile or environment in which a bean is active.

• The annotation is used in conjunction with @Component or @Configuration annotations.

• A bean annotated with @Profile will only be created if the specified profile(s) are active in the application context.

• Using this annotation one can define different beans for various environments, such as development, testing, or production.

Difference between @Component @Bean and @Profile in Spring Framework




Example of @Bean, @Component, and @Profile annotation in Spring

Let’s understand these annotations with the help of an example;

@Bean  Annotation Example

Here is an example of @Bean annotation in Spring Framework:

@Configuration
public class AppConfig {

@Bean(name = "dataSource")
public DataSource getDataSource() {

// create and configure a data source object
DataSource dataSource = new DataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/mydb");
dataSource.setUsername("root");
dataSource.setPassword("password");

return dataSource;
}

}


In the above example, the @Bean annotation is used to declare a bean named dataSource. The getDataSource() method creates and configures a DataSource object, which is then registered as a bean in the application context.

Example 02 - Creating custom Bean

Let's say we want to create a custom bean that represents a car with a specific model, make, and year. We can use @Bean annotation to create and configure this bean in a configuration class:

@Configuration
public class CarConfig {

  @Bean
  public Car myCar() {
     return new Car("Toyota", "Camry", 2022);
  }
}


This creates a Car bean with the specified model, make, and year that we can then use throughout our application.


@Component Example

Here is an example of @Component example in Spring Framework

@Component
public class Customer {
private String firstName;
private String lastName;

public String getFirstName() {
   return firstName;
}

public void setFirstName(String firstName) {
  this.firstName = firstName;
}

public String getLastName() {
   return lastName;
}

public void setLastName(String lastName) {
  this.lastName = lastName;
}

}


In the above example, the @Component annotation is used to mark the Customer class as a Spring-managed component. The Customer class can be automatically detected during component scanning and registered as a bean in the application context.


Example 02 of @Component Example

Here is another example of @Component annotation in Spring Framework:

@Component
public class User {
private String username;
private String password;

// getters and setters
}

This marks the User class as a Spring-managed component that can be automatically detected during component scanning.


@Profile Annotation Example

Here is another example of @Profile annotation in Spring framework:

@Configuration
public class AppConfig {

@Bean(name = "dataSource")
@Profile("prod")
public DataSource getProdDataSource() {
// create and configure a production data source object
DataSource dataSource = new DataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://prod-server:3306/mydb");
dataSource.setUsername("prod-user");
dataSource.setPassword("prod-password");
return dataSource;
}



@Bean(name = "dataSource")
@Profile("dev")
public DataSource getDevDataSource() {
// create and configure a development data source object
DataSource dataSource = new DataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://dev-server:3306/mydb");
dataSource.setUsername("dev-user");
dataSource.setPassword("dev-password");
return dataSource;
}

}

In the above example, the @Profile annotation is used to specify the environment or configuration profile in which a bean is active. The getProdDataSource() method creates and configures a production data source object, which is registered as a bean only when the prod profile is active in the application context. 

Similarly, the getDevDataSource() method creates and configures a development data source object, which is registered as a bean only when the dev profile is active in the application context. This allows for different beans to be registered based on the active profile, which can be useful for managing different environments such as development, testing, and production.




Difference between @Bean, @Component and @Profile in Spring Framework

Let’s understand the difference between these annotations based on following categories;

Purpose
• A single bean may be directly created and configured in a configuration class using the @Bean keyword.

• When a class is marked with the attribute @Component, it is instantly recognized as a Spring-managed component during component scanning.

• The environment or configuration profile in which a bean is active is specified using the @Profile macro.

Usage
• Beans are widely used in Java Configuration classes, but they can also be used in XML based configurations.

• Domain objects and utility classes frequently utilize the annotation @Component.

• Based on the active profile Beans are conditionally created using the annotation @Profile in combination with @Component or @Configuration annotations.

Scoped
• Singleton, prototype, and other sorts of beans may be made with @Bean.

• In addition to creating singleton beans by default, @Component may also be used to construct a prototype, request, session, and global session beans when combined with additional scope annotations.

• Bean scope is unaffected by @Profile, however, it may be used to generate or exclude beans based on the active profiles.

Naming
• By utilizing the name property, @Bean enables explicit setting of the bean name.

• @Component does not allow users to set the bean name explicitly. By default, it will be the same as the class name but with a lowercase first letter.

• Bean naming is unaffected by @Profile.


If you need more differences then here is a nice table which summarizes the difference between @Bean and @Component annotations in Spring Framework:






Final Words
That's all about difference between @Bean, @Component, and @Profile annotation in Spring Framework. In conclusion, the annotations @Bean, @Component, and @Profile have various functions in a Spring application. To explicitly construct and configure a single bean, use @Bean. To identify classes as Spring-managed components, use @Component. To provide the current environment or configuration profile, use @Profile. 

When developing and maintaining Spring applications, it's crucial to comprehend the variations between these annotations.  

We appreciate your valuable time, I hope this effort has improved your understanding of this topic.

Other Spring MVC articles and Tutorials you may like

Thanks a lot for reading this article so far. If you like this Java and Spring MVC interview question discussion and tutorial then please share them with your friends and colleagues. If you have any questions or feedback then please drop a note.

No comments :

Post a Comment