方法注入

在大多数应用场景中,容器中的大多数 bean 都是 单例。当一个 单例 bean 需要与另一个单例 bean 协作,或者一个非单例 bean 需要与另一个非单例 bean 协作时,您通常通过将一个 bean 定义为 另一个 bean 的属性来处理依赖关系。当 bean 生命周期 不同时,就会出现问题。假设单例 bean A 需要使用非单例(原型)bean B, 可能是在 A 的每次方法调用时。容器只创建单例 bean A 一次, 因此只有一次机会设置属性。容器不能 在每次需要时都为 bean A 提供一个新的 bean B 实例。 一个解决方案是放弃一些控制反转。您可以 使 bean A 了解容器 通过实现 ApplicationContextAware 接口, 并通过 对容器进行 getBean("B") 调用 每次 bean A 需要时 请求(通常是新的)bean B 实例。以下示例 显示了这种方法:

  • Java

  • Kotlin

package fiona.apple;

// Spring-API imports
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * A class that uses a stateful Command-style class to perform
 * some processing.
 */
public class CommandManager implements ApplicationContextAware {

	private ApplicationContext applicationContext;

	public Object process(Map commandState) {
		// grab a new instance of the appropriate Command
		Command command = createCommand();
		// set the state on the (hopefully brand new) Command instance
		command.setState(commandState);
		return command.execute();
	}

	protected Command createCommand() {
		// notice the Spring API dependency!
		return this.applicationContext.getBean("command", Command.class);
	}

	public void setApplicationContext(
			ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}
}
package fiona.apple

// Spring-API imports
import org.springframework.context.ApplicationContext
import org.springframework.context.ApplicationContextAware

// A class that uses a stateful Command-style class to perform
// some processing.
class CommandManager : ApplicationContextAware {

	private lateinit var applicationContext: ApplicationContext

	fun process(commandState: Map<*, *>): Any {
		// grab a new instance of the appropriate Command
		val command = createCommand()
		// set the state on the (hopefully brand new) Command instance
		command.state = commandState
		return command.execute()
	}

	// notice the Spring API dependency!
	protected fun createCommand() =
			applicationContext.getBean("command", Command::class.java)

	override fun setApplicationContext(applicationContext: ApplicationContext) {
		this.applicationContext = applicationContext
	}
}

前面的做法并不可取,因为业务代码了解并耦合到 Spring 框架。方法注入是 Spring IoC 容器的一个稍微高级的功能,它允许您干净地处理此用例。 您可以在 这篇博客文章 中阅读有关方法注入动机的更多信息。

查找方法注入

查找方法注入是容器覆盖 容器管理 bean 中的方法并返回容器中另一个命名 bean 的查找结果的能力。 查找通常涉及原型 bean,如 上一节 中描述的场景。Spring 框架 通过使用 CGLIB 库的字节码生成来动态生成覆盖该方法的子类,从而实现此方法注入。

  • 为了使这种动态子类化工作,Spring bean 容器 子类化的类不能是 final,并且要被覆盖的方法也不能是 final

  • 单元测试具有 abstract 方法的类需要您自己子类化该类 并提供 abstract 方法的存根实现。

  • 另一个关键限制是查找方法不适用于工厂方法, 特别是配置类中的 @Bean 方法,因为在这种情况下, 容器不负责创建实例,因此无法 即时创建运行时生成的子类。

在前面代码片段中的 CommandManager 类中, Spring 容器动态覆盖了 createCommand() 方法的实现。 CommandManager 类没有任何 Spring 依赖项,如 修改后的示例所示:

  • Java

  • Kotlin

package fiona.apple;

// no more Spring imports!

public abstract class CommandManager {

	public Object process(Object commandState) {
		// grab a new instance of the appropriate Command interface
		Command command = createCommand();
		// set the state on the (hopefully brand new) Command instance
		command.setState(commandState);
		return command.execute();
	}

	// okay... but where is the implementation of this method?
	protected abstract Command createCommand();
}
package fiona.apple

// no more Spring imports!

abstract class CommandManager {

	fun process(commandState: Any): Any {
		// grab a new instance of the appropriate Command interface
		val command = createCommand()
		// set the state on the (hopefully brand new) Command instance
		command.state = commandState
		return command.execute()
	}

	// okay... but where is the implementation of this method?
	protected abstract fun createCommand(): Command
}

在包含要注入的方法的客户端类(本例中为 CommandManager)中, 要注入的方法需要以下形式的签名:

<public|protected> [abstract] <return-type> theMethodName(no-arguments);

如果该方法是 abstract,则动态生成的子类实现该方法。 否则,动态生成的子类会覆盖原始类中定义的具体方法。 考虑以下示例:

<!-- a stateful bean deployed as a prototype (non-singleton) -->
<bean id="myCommand" class="fiona.apple.AsyncCommand" scope="prototype">
	<!-- inject dependencies here as required -->
</bean>

<!-- commandManager uses myCommand prototype bean -->
<bean id="commandManager" class="fiona.apple.CommandManager">
	<lookup-method name="createCommand" bean="myCommand"/>
</bean>

标识为 commandManager 的 bean 在每次需要 myCommand bean 的新实例时 都会调用其自己的 createCommand() 方法。如果确实需要, 您必须小心将 myCommand bean 部署为原型。如果它是 一个 单例,则每次都返回 myCommand bean 的相同实例。

或者,在基于注解的组件模型中,您可以通过 @Lookup 注解声明一个查找 方法,如以下示例所示:

  • Java

  • Kotlin

public abstract class CommandManager {

	public Object process(Object commandState) {
		Command command = createCommand();
		command.setState(commandState);
		return command.execute();
	}

	@Lookup("myCommand")
	protected abstract Command createCommand();
}
abstract class CommandManager {

	fun process(commandState: Any): Any {
		val command = createCommand()
		command.state = commandState
		return command.execute()
	}

	@Lookup("myCommand")
	protected abstract fun createCommand(): Command
}

或者,更惯用地,您可以依赖于目标 bean 根据 查找方法的声明返回类型解析,如以下示例所示:

  • Java

  • Kotlin

public abstract class CommandManager {

	public Object process(Object commandState) {
		Command command = createCommand();
		command.setState(commandState);
		return command.execute();
	}

	@Lookup
	protected abstract Command createCommand();
}
abstract class CommandManager {

	fun process(commandState: Any): Any {
		val command = createCommand()
		command.state = commandState
		return command.execute()
	}

	@Lookup
	protected abstract fun createCommand(): Command
}

另一种访问不同作用域目标 bean 的方法是 ObjectFactory/ Provider 注入点。请参阅 作为依赖项的作用域 bean。 您可能还会发现 ServiceLocatorFactoryBean(在 org.springframework.beans.factory.config 包中)很有用。

任意方法替换

一种不如查找方法注入有用的方法注入形式是能够 用另一种方法实现替换托管 bean 中的任意方法。您 可以安全地跳过本节的其余部分,直到您实际需要此功能。

通过基于 XML 的配置元数据,您可以使用 replaced-method 元素 替换已部署 bean 的现有方法实现。考虑 以下类,它有一个名为 computeValue 的方法,我们想要覆盖它:

  • Java

  • Kotlin

public class MyValueCalculator {

	public String computeValue(String input) {
		// some real code...
	}

	// some other methods...
}
class MyValueCalculator {

	fun computeValue(input: String): String {
		// some real code...
	}

	// some other methods...
}

实现 org.springframework.beans.factory.support.MethodReplacer 接口的类提供了新的方法定义,如以下示例所示:

  • Java

  • Kotlin

/**
 * meant to be used to override the existing computeValue(String)
 * implementation in MyValueCalculator
 */
public class ReplacementComputeValue implements MethodReplacer {

	public Object reimplement(Object o, Method m, Object[] args) throws Throwable {
		// get the input value, work with it, and return a computed result
		String input = (String) args[0];
		...
		return ...;
	}
}
/**
 * meant to be used to override the existing computeValue(String)
 * implementation in MyValueCalculator
 */
class ReplacementComputeValue : MethodReplacer {

	override fun reimplement(obj: Any, method: Method, args: Array<out Any>): Any {
		// get the input value, work with it, and return a computed result
		val input = args[0] as String;
		...
		return ...;
	}
}

部署原始类并指定方法覆盖的 bean 定义将 类似于以下示例:

<bean id="myValueCalculator" class="x.y.z.MyValueCalculator">
	<!-- arbitrary method replacement -->
	<replaced-method name="computeValue" replacer="replacementComputeValue">
		<arg-type>String</arg-type>
	</replaced-method>
</bean>

<bean id="replacementComputeValue" class="a.b.c.ReplacementComputeValue"/>

您可以在 <replaced-method/> 元素中使用一个或多个 <arg-type/> 元素来指示要覆盖的方法的签名。 仅当方法重载且类中存在多个变体时,才需要参数签名。 为方便起见,参数的类型字符串可以是完全限定类型名称的子字符串。 例如,以下所有都匹配 java.lang.String

java.lang.String
String
Str

因为参数的数量通常足以区分每个可能的 选择,所以这种快捷方式可以节省大量的输入,允许您只输入 与参数类型匹配的最短字符串。