对于最新的稳定版本,请使用 Spring Framework 7.0.6!spring-doc.cadn.net.cn

方法注入

在大多数应用场景中,容器中的大多数bean都是 单例。当一个单例bean需要与另一个单例bean协作,或者一个非单例bean需要与另一个非单例bean协作时,通常通过将其中一个bean定义为另一个的属性来处理依赖关系。当bean的生命周期不同时,就会出现问题。假设单例bean A需要使用非单例(原型)bean B,可能在每次调用A的方法时都需要。容器只创建单例bean A一次,因此只有一次机会设置属性。容器无法在每次需要时为bean A提供一个新的bean B实例。spring-doc.cadn.net.cn

一种解决方案是放弃一些控制反转。你可以通过实现 ApplicationContextAware 接口,让 bean A 了解容器,以及通过 对容器进行 getBean("B") 调用,在 bean A 需要它时每次请求(通常是新的)bean B 实例。下面的例子展示了这种方法:spring-doc.cadn.net.cn

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容器的一个较为高级的功能,它可以让您以更清晰的方式处理这种情况。spring-doc.cadn.net.cn

您可以阅读有关方法注入动机的更多信息, 这篇博客文章spring-doc.cadn.net.cn

查找方法注入

查找方法注入是容器覆盖容器管理的bean上的方法并返回容器中另一个命名bean的查找结果的能力。查找通常涉及一个原型bean,如< a t="C0">上一节所述的情况。Spring框架通过使用CGLIB库的字节码生成来实现此方法注入,以动态生成覆盖该方法的子类。spring-doc.cadn.net.cn

  • 为了使这种动态子类化正常工作,Spring bean 容器所继承的类不能是 final,并且要覆盖的方法也不能是 finalspring-doc.cadn.net.cn

  • 对包含abstract方法的类进行单元测试需要您自己继承该类,并提供abstract方法的模拟实现。spring-doc.cadn.net.cn

  • 具体方法对于组件扫描也是必要的,这需要具体的类来识别。spring-doc.cadn.net.cn

  • 另一个关键限制是,查找方法无法与工厂方法一起使用,特别是不能与配置类中的@Bean方法一起使用,因为在这种情况下,容器不负责创建实例,因此无法动态生成子类。spring-doc.cadn.net.cn

在前一个代码片段中的 CommandManager 类的情况下,Spring 容器会动态覆盖 createCommand() 方法的实现。CommandManager 类没有任何 Spring 依赖,正如重新设计的示例所示:spring-doc.cadn.net.cn

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),要注入的方法需要以下形式的签名:spring-doc.cadn.net.cn

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

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

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

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

被标识为 commandManager 的 Bean 在需要 myCommand Bean 的新实例时会调用其自身的 createCommand() 方法。您必须小心,如果确实需要的话,应将 myCommand Bean 部署为原型。如果是 单例,每次都会返回 myCommand Bean 的同一实例。spring-doc.cadn.net.cn

或者,在基于注解的组件模型中,你可以通过 @Lookup 注解声明一个查找方法,如下例所示:spring-doc.cadn.net.cn

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 根据查找方法声明的返回类型进行解析:spring-doc.cadn.net.cn

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
}

请注意,通常应使用具体的存根实现来声明此类带注解的查找方法,以便它们与 Spring 的组件扫描规则兼容,默认情况下会忽略抽象类。此限制不适用于显式注册或显式导入的 bean 类。spring-doc.cadn.net.cn

访问不同作用域目标Bean的另一种方法是ObjectFactory/Provider注入点。参见作用域Bean作为依赖项spring-doc.cadn.net.cn

您可能还会发现 ServiceLocatorFactoryBean(在 org.springframework.beans.factory.config 包中)很有用。spring-doc.cadn.net.cn

任意方法替换

比查找方法注入更不常用的一种方法注入形式是能够将托管Bean中的任意方法替换为另一个方法实现。你可以安全地跳过本节的其余内容,直到你实际需要此功能为止。spring-doc.cadn.net.cn

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

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 接口的类提供了新的方法定义,如下例所示:spring-doc.cadn.net.cn

/**
 * 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 定义将类似于以下示例:spring-doc.cadn.net.cn

<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"/>

您可以使用一个或多个 <arg-type/> 元素在 <replaced-method/> 元素内来指示被覆盖方法的方法签名。如果方法被重载并且类中存在多个变体,则需要指定参数的签名。为了方便,参数的类型字符串可以是完全限定类型名称的子串。例如,以下都匹配 java.lang.Stringspring-doc.cadn.net.cn

java.lang.String
String
Str

由于参数的数量通常足以区分每个可能的选择,通过只输入匹配参数类型的最短字符串,这个快捷方式可以节省大量输入时间。spring-doc.cadn.net.cn