Spring – Beans using @Bean

Spring – Beans using @Bean

We have previously discussed an example of Spring configuration using an XML-based configuration. In the previous example, we have defined beans inside the bean-configuration file (applicationContext.xml). To make the code easier and understandable, we are going to use @Bean annotation (annotation-based configuration) for configuring Spring applications.  

@Bean – The @Bean is a method level annotation. It tells the Spring container that the annotated method will return a bean. To define a bean, annotate a method with @Bean annotation. The method name must be the same as the bean name. It also supports several attributes provided by the <bean> tag such as init-method, destroy-method, dependency, and autowiring.

Let’s understand the concept of @Bean annotation through an example.

Example of Spring beans using @Bean annotation

Here, we are going to create an example of Spring beans using @Bean annotation. The Fortune.java and Coach.java are the two interfaces that contain the unimplemented methods, and GoodLuckFortune.java and Cricket_Coach.java are the Java classes that implement the Fortune and Coach interface, respectively. The class AppConfig.java is a Java-based configuration class that contains the bean information.

Following are the steps to create an example of Spring beans using @Bean:

  • Create an Interface

In this step, we are going to create an interface named Fortune.java.

Fortune.java

public interface Fortune {
public String getDailyFortune();
}
  • Create a Java class

In this step, we are going to create a class named GoodLuckFortune.java that implements the Fortune interface.

GoodLuckFortune.java

import org.springframework.stereotype.Component;
@Component
public class GoodLuckFortune implements Fortune{
public String getDailyFortune() {
return "Goodluck For today..!!" ;
}
} 
  • Create another Interface

In this step, we are going to create another interface named Coach.java.

Coach.java

public interface Coach {
public String getDailyTraining();
public String getFortuneService();
} 
  • Create another Java class

In this step, we are going to create another Java class named Cricket_Coach.java that implements the Coach interface.

Cricket_Coach.java

import org.springframework.stereotype.Component;
@Component
public class Cricket_Coach implements Coach {
private Fortune fortuneService;
public Cricket_Coach(Fortune fortuneService) {
this.fortuneService = fortuneService;
}
public String getDailyTraining() { 
return "Daily 5 hours of running..!" ;
}
public String getFortuneService() {
return fortuneService.getDailyFortune() ;
}
} 
  • Create the Configuration class

In this step, we are going to create the configuration class named AppConfig.java.

AppConfig.java

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan( "com.app.SpringBean_usingBean" )
public class AppConfig {
// defining bean for GoodLuckFortune class 
@Bean
public Fortune goodLuckFortune() {
return new GoodLuckFortune();
}
//defining bean for Cricket_Coach class
@Bean 
public Coach cricket_Coach() {
return new Cricket_Coach(goodLuckFortune());
}
} 

In the AppConfig.java file, we have declared the bean classes, one is GoodLuckFortune, and the other is Cricket_Coach. The bean name and the method name (on which @Bean is defined) are must be the same as defined in the above code.

  • Create the main class

In this step, we are going the main class named App.java.

App.java

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class App 
{
public static void main( String[] args )
{
AnnotationConfigApplicationContext appcontext = new AnnotationConfigApplicationContext(AppConfig.class);
Coach newCoach = appcontext.getBean("cricket_Coach", Coach.class); 
System.out.println(newCoach.getDailyTraining());
System.out.println(newCoach.getFortuneService());
appcontext.close();
}
} 

Output

main class named App.java


Related Topics

Spring - Bean Scope

Spring - Bean Scope Bean Scope refers to a lifecycle of the bean. It allows us to have control over the creation of bean objects. It is a very powerful approach and provides...

6 minutes read.

Spring AOP – @Before Advice Type

Spring AOP – @Before Advice Type As we have discussed, AOP (Aspect-Oriented Programming) is one of the powerful features of the Spring framework. It complements the Object-Oriented Programming (OOPs). AOP provides some concepts and terminology,...

2 minutes read.

Spring MVC Form – Drop-Down List

We have already discussed the Spring MVC form tags available in the form tag library. Form tags are used to develop web applications easily. In this tutorial, we are going to discuss the...

13 minutes read.

Spring MVC Form Validation

Spring Validation is used to validate the @Controller inputs. It is used to check and accept the user input in any web application. Using Spring validation, we can validate the user input on...

12 minutes read.

Spring MVC Example – Reading HTML Form Data

We have discussed earlier a simple example of Spring MVC in which we have created multiple view pages. Here, we are going to create another Spring MVC example in which we are...

7 minutes read.

Spring MVC Tutorial

Spring MVC is a web Model-View-Controller framework built on Servlet API. It is used to build web applications. The MVC framework works around central servlet called DispatcherServlet. It dispatches the requests to the...

4 minutes read.

Spring Autowiring –Field Injection

Spring Autowiring –Field Injection The Field Injection is used to inject the fields, variables, or properties of the beans. It is not available in autowiring using XML- based configuration. It is a...

2 minutes read.

Spring MVC Form Tag Library

The Spring MVC provides a variety of tags available in the form of a tag library, which is used to develop web pages (JSP view pages). The Spring’s form tag...

6 minutes read.

Spring MVC Example

Spring MVC Example We have previously discussed the Spring Web MVC framework. In this tutorial, we are going to create a simple example of Spring Web MVC. Following are the steps used to create an example...

2 minutes read.

Spring – Beans using @Bean

Spring – Beans using @Bean We have previously discussed an example of Spring configuration using an XML-based configuration. In the previous example, we have defined beans inside the bean-configuration file (applicationContext.xml). To make the...

3 minutes read.

Spring - Inversion of Control (IoC)

Spring - Inversion of Control (IoC) The Inversion of Control (IoC) is a process where the objects define their dependencies, that is, the dependencies of other objects with they are working. It is done...

4 minutes read.

Spring Model Interface

Model Interface Model is an interface that defines a holder for model attributes. It is also used to transfer data between various parts of the Spring MVC application. The Model interface is available...

8 minutes read.

Spring Autowiring – Constructor Injection

Spring Autowiring – Constructor Injection We have previously discussed an example of Constructor Dependency Injection (CDI) using an XML-based configuration. In the previous case, we have defined the reference of the constructor in...

2 minutes read.

Spring AOP – @AfterReturning Advice

Spring AOP – @AfterReturning Advice We have discussed earlier the types of advices available in Spring AOP. One of them is After Returning advice. It is an advice that executes after the normal execution...

3 minutes read.

Spring MVC Form Text Field

We have previously discussed the Spring MVC form tags. The form tag library provides a variety of form tags that are used to build web applications. One of them is a <form:input>...

8 minutes read.

Spring AOP – Pointcut Expressions

Spring AOP – Pointcut Expressions Pointcut refers to a collection of join points that specify where advice to be applied. In other words, pointcut represents a set of various join points. It defines that...

7 minutes read.

Spring - Bean lifecycle using annotations

Spring - Bean lifecycle using annotations We have already discussed the bean lifecycle using an XML-based configuration. In the previous case, we have declared the init-method and destroy-method attributes in the bean-configuration file. Here, we...

2 minutes read.

Spring MVC Form Checkbox

Spring MVC provides several form tags used to develop web applications (Usually JSP pages). One of them is a checkbox tag. The checkbox tag offers us to choose multiple options at the same...

12 minutes read.

Spring – Configuration using @Configuration

Spring – Configuration using @Configuration We have previously discussed the Spring configuration using an XML configuration file. In that case, we have defined all the bean information in the bean-configuration file (applicationContext.xml). ...

3 minutes read.

Spring - Injecting values from Property Files

Spring - Injecting values from Property Files In this section, we will discuss how to inject values from a property file using the Java-based configuration. Here, we will use two annotations @Value and @PropertySource...

3 minutes read.