Implementing instance factory method using Spring annotations

In this post under Spring Core, I will show how to implement instance 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 instance factory method

Calculator

package core.package53;

public class Calculator {
    public void calculate() {
        System.out.println("Calculating....");
    }
}

Below is the factory class that will create “Calculator” instance.

CalculatorFactory

package core.package53;

public class CalculatorFactory {
    public Calculator createCalculator() {
        return new Calculator();
    }
}

Below is the main class that shows how to implement instance factory method

Main class

package core.package53;

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.package53")
public class Example53 {
    @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 14, I create “calculatorFactory” method annotated with “@Bean” annotation. This method will create and return an instance of “CalculatorFactory” class.

At line 19, I create “calculator” method annotated with “@Bean” annotation. This method will take an instance of “CalculatorFactory” as method argument autowired by Spring.

In this method, using the “CalculatorFactory” instance, the method creates and returns an instance of “Calculator” class by calling non-static “createCalculator” method available on “CalculatorFactory”
class.

Now when I call “getBean” at line 25 and pass “Calculator” class object, Spring will call “calculator” method to create and return a new instance of “Calculator” class using the “CalculatorFactory”
instance.

In this way we can implement instance factory method using Spring annotations.

Leave a comment