In this post under Spring Core, I will show how to implement static factory method using Spring annotations instead of using xml approach.
For our example, lets create “Calculator” class with below structure, whose bean we have to create using factory method
Calculator
package core.package52;
public class Calculator {
public void calculate() {
System.out.println("Calculating....");
}
}
Below is the factory class that will create “Calculator” instance.
CalculatorFactory
package core.package52;
public class CalculatorFactory {
public static Calculator createCalculator() {
return new Calculator();
}
}
Below is the main class that shows how to implement static factory method
Main class
package core.package52;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "core.package52")
public class Example52 {
@Bean
public Calculator calculator() {
return CalculatorFactory.createCalculator();
}
public static void main(String[] args) {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Example52.class);
Calculator calculator = applicationContext.getBean(Calculator.class);
calculator.calculate();
}
}
In the above code, at line 13, I create a method “calculator” annotated it with “@Bean” annotation.
Inside the method, I am calling “CalculatorFactory” class “createCalculator” method to create an instance of “Calculator” class.
This newly created “Calculator” class instance will be return value of “calculator” method.
At line 19, when I call “getBean” and pass “Calculator” class object as an argument, Spring calls the “calculator” method to get an instance of “Calculator” class.
In this way we can implement factory method using Spring annotations.