Spring Dependency Injection 简明教程

Spring DI - Non-Static Factory

Spring 提供了一个选项,可以使用工厂方法和工厂 bean 属性注入依赖项,以用于非静态工厂方法。

Example

以下示例展示了 TextEditor 类,它只能使用纯基于 setter 的注入进行依赖项注入。

让我们更新在 Spring DI - Create Project 章节中创建的项目。我们将添加以下文件 −

  1. TextEditor.java − 包含 SpellChecker 作为依赖项的类。

  2. SpellChecker.java − 依赖项类。

  3. MainApp.java - 要运行和测试的主应用。

以下为 TextEditor.java 文件的内容 −

package com.tutorialspoint;

public class TextEditor {
   private SpellChecker spellChecker;
   private String name;

   public void setSpellChecker( SpellChecker spellChecker ){
      this.spellChecker = spellChecker;
   }
   public SpellChecker getSpellChecker() {
      return spellChecker;
   }
   public void setName(String name) {
      this.name = name;
   }
   public String getName() {
      return name;
   }
   public void spellCheck() {
      spellChecker.checkSpelling();
   }
}

以下是另一个依赖类文件 SpellChecker.java 的内容 −

这个类构造函数是私有的。因此,无法使用 new 操作符直接使用它创建其他对象。它使用非静态工厂方法来获取一个实例。

package com.tutorialspoint;

public class SpellChecker {
   private SpellChecker(){
      System.out.println("Inside SpellChecker constructor." );
   }
   public SpellChecker getInstance() {
      System.out.println("Inside SpellChecker getInstance." );
      return new SpellChecker();
   }
   public void checkSpelling(){
      System.out.println("Inside checkSpelling." );
   }
}

以下是 MainApp.java 文件的内容−

package com.tutorialspoint;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("applicationcontext.xml");
      TextEditor te = (TextEditor) context.getBean("textEditor");
      te.spellCheck();
   }
}

下面是配置了自动装配的配置 applicationcontext.xml

<?xml version = "1.0" encoding = "UTF-8"?>

<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <!-- Definition for textEditor bean -->
   <bean id = "textEditor" class = "com.tutorialspoint.TextEditor" autowire = "byName">
      <property name = "name" value = "Generic Text Editor" />
   </bean>

   <bean id = "spellCheckFactory" class = "com.tutorialspoint.SpellChecker"></bean>

   <!-- Definition for spellChecker bean -->
   <bean id = "spellChecker" class = "com.tutorialspoint.SpellChecker" factory-method="getInstance">< factory-bean="spellCheckFactory"/bean>
</beans>

Output

完成源文件和 Bean 配置文件创建后,我们运行该应用程序。如果您的应用程序一切正常,它将打印以下消息−

Inside SpellChecker constructor.
Inside SpellChecker getInstance.
Inside SpellChecker constructor.
Inside checkSpelling.