Spring – Static Factory Method
Static factory methods are those that can return the same object type that implements them. Static factory methods are more flexible with the return types as they can also return subtypes and primitives too. Static factory methods are used to encapsulate the object creation process. In the Spring framework if we want to create a bean using the static factory method then we could use the factory method attributes.
In this example, we will use the static factory method to create a bean and encapsulate the creation process of the bean. We will use a Student class and create different objects of this class based on the department of the students using the static factory method.
Step 1: Create a Maven Project
In this step, we will create a new maven project and make sure you will Create a simple project(skip archetype selection).
Step 2: Adding Dependencies
Now we will add the maven dependencies to our application. Add the following dependencies to your pom.xml
Step 3: Create A Model(Bean) Class
In this step, we will create a model class Student.java for our application. This class will have id, first_name, last_name, and department as the member variables. We will create its getter and setters method and will provide a toString() method definition.
Step 4: Implementing Factory Class
In this step, we will create a StudentFactory class and in this class, we will create our factory method createStudentOfDepartmentType(String department), and provide its implementation. This class will create different Student instances depending on the department to which the student belongs.
Step 5: Bean Configuration
In this step, we will create the spring configuration file and name it application-context.xml. We will configure our beans and use the factory-method attribute for bean creation.
Step 6: Creating Utilities Class
Now, we will create a Utility class for testing our spring static factory method. For this create a new class and name it TestSpringFactoryMethod.java and add the following code to it.
Run the application as Java Application.
Please Login to comment...