📜  Spring – 静态工厂方法

📅  最后修改于: 2022-05-13 01:55:41.430000             🧑  作者: Mango

Spring – 静态工厂方法

静态工厂方法是那些可以返回实现它们的相同对象类型的方法。静态工厂方法在返回类型方面更加灵活,因为它们也可以返回子类型和原语。静态工厂方法用于封装对象创建过程。在 Spring 框架中,如果我们想使用静态工厂方法创建 bean,那么我们可以使用工厂方法属性。

例子

在这个例子中,我们将使用静态工厂方法来创建一个bean,并封装bean的创建过程。我们将使用一个 Student 类,并使用静态工厂方法根据学生所在的部门创建该类的不同对象。

第 1 步:创建一个 Maven 项目

在这一步中,我们将创建一个新的 maven 项目,并确保您将创建一个简单的项目(跳过原型选择)。

项目描述

图 1 – 项目描述

第 2 步:添加依赖项

现在我们将 Maven 依赖项添加到我们的应用程序中。将以下依赖项添加到您的 pom.xml

XML

  4.0.0
  com.geeksforgeeks
  GeeksForGeeks
  0.0.1-SNAPSHOT
   
  
   
    
    
            org.springframework
            spring-beans
            5.0.8.RELEASE
    
     
    
    
            org.springframework
            spring-context
            5.0.8.RELEASE
    
 
  


Java
public class Student {
 
    // member variable
    private int id;
    private String first_name;
    private String last_name;
    private String department;
   
    // getters and setters
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getFirst_name() {
        return first_name;
    }
    public void setFirst_name(String first_name) {
        this.first_name = first_name;
    }
    public String getLast_name() {
        return last_name;
    }
    public void setLast_name(String last_name) {
        this.last_name = last_name;
    }
    public String getDepartment() {
        return department;
    }
    public void setDepartment(String department) {
        this.department = department;
    }
   
    // toStirng() method
    @Override
    public String toString() {
        return "Student [id=" + id + ", first_name=" + first_name + ",
                  last_name=" + last_name + ", department="
                + department + "]";
    }
 
}


Java
public class StudentFactory {
     
    public static Student createStudentOfDepartmentType(String department) {
       
        // Student instance
        Student student = null;
       
        // if student belongs to CSE department
        if(department.equals("CSE")) {
            student = new Student();
            student.setId(1);
            student.setFirst_name("geeks");
            student.setLast_name("geeks");
            student.setDepartment(department);
        }
       
        // if student belongs to MECH department
        else if(department.equals("MECH")) {
            student = new Student();
            student.setId(2);
            student.setFirst_name("dummy");
            student.setLast_name("dummy");
            student.setDepartment(department);
        }
       
        // if department passed through
        // beans is not known it will
        // throw an exception
        else {
            throw new IllegalArgumentException("Unknown department");
        }
        return student;
    }
}


XML


   
    
        
    
      
    
        
    
   


Java
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
import com.gfg.model.Student;
public class TestSpringFactoryMethod {
 
    @SuppressWarnings("resource")
    public static void main(String []args) throws Exception {
         
        // Reading the application-context file
        // using class path of spring context xml file
        AbstractApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
         
        // Spring check the blueprint for Student bean
        // from application-context.xml file and return it
        Student computer_student = (Student)context.getBean("CSE");
        System.out.println(computer_student.toString());
         
        Student mechanical_student = (Student)context.getBean("MECH");
        System.out.println(mechanical_student.toString());
         
    }
}



第 3 步:创建模型(Bean)类

在这一步中,我们将创建一个模型类 Student。我们的应用程序的Java 。此类将具有 id、first_name、last_name 和部门作为成员变量。我们将创建它的 getter 和 setters 方法,并提供一个 toString() 方法定义。

Java

public class Student {
 
    // member variable
    private int id;
    private String first_name;
    private String last_name;
    private String department;
   
    // getters and setters
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getFirst_name() {
        return first_name;
    }
    public void setFirst_name(String first_name) {
        this.first_name = first_name;
    }
    public String getLast_name() {
        return last_name;
    }
    public void setLast_name(String last_name) {
        this.last_name = last_name;
    }
    public String getDepartment() {
        return department;
    }
    public void setDepartment(String department) {
        this.department = department;
    }
   
    // toStirng() method
    @Override
    public String toString() {
        return "Student [id=" + id + ", first_name=" + first_name + ",
                  last_name=" + last_name + ", department="
                + department + "]";
    }
 
}


第四步:实现工厂类

在这一步中,我们将创建一个StudentFactory类,在这个类中,我们将创建我们的工厂方法createStudentOfDepartmentType(String department) ,并提供它的实现。这个类将根据学生所属的部门创建不同的学生实例。

Java

public class StudentFactory {
     
    public static Student createStudentOfDepartmentType(String department) {
       
        // Student instance
        Student student = null;
       
        // if student belongs to CSE department
        if(department.equals("CSE")) {
            student = new Student();
            student.setId(1);
            student.setFirst_name("geeks");
            student.setLast_name("geeks");
            student.setDepartment(department);
        }
       
        // if student belongs to MECH department
        else if(department.equals("MECH")) {
            student = new Student();
            student.setId(2);
            student.setFirst_name("dummy");
            student.setLast_name("dummy");
            student.setDepartment(department);
        }
       
        // if department passed through
        // beans is not known it will
        // throw an exception
        else {
            throw new IllegalArgumentException("Unknown department");
        }
        return student;
    }
}

第 5 步:Bean 配置

在这一步中,我们将创建 spring 配置文件并将其命名为application-contex.xml 。我们将配置我们的 bean 并使用 factory-method 属性来创建 bean。

XML



   
    
        
    
      
    
        
    
   


第 6 步:创建实用程序类

现在,我们将创建一个 Utility 类来测试我们的 spring 静态工厂方法。为此创建一个新类并将其命名为TestSpringFactoryMethod。 Java并将以下代码添加到其中。

Java

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
import com.gfg.model.Student;
public class TestSpringFactoryMethod {
 
    @SuppressWarnings("resource")
    public static void main(String []args) throws Exception {
         
        // Reading the application-context file
        // using class path of spring context xml file
        AbstractApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
         
        // Spring check the blueprint for Student bean
        // from application-context.xml file and return it
        Student computer_student = (Student)context.getBean("CSE");
        System.out.println(computer_student.toString());
         
        Student mechanical_student = (Student)context.getBean("MECH");
        System.out.println(mechanical_student.toString());
         
    }
}

输出:

将应用程序作为Java应用程序运行。

输出