大多数情况下Spring所生产出的实例都为单例。
查找方法注入
-
Spring可将bean中方法进行替换,篡改为Spring所规定的bean。
-
所进行方法替换的bean不可为final,且其子类不可为final,即其可存在子类继承。
-
对于抽象类,需要其存在一个实际的实现类方可。
-
且方法的替换无法对工厂方法进行修改,且不能对添加了@Bean注解的类进行修改。
-
在bean中使用lookup-method标签可修改方法返回值为指定类型:
<bean id="myCommand" class="fiona.apple.AsyncCommand" scope="prototype"></bean> <bean id="commandManager" class="fiona.apple.CommandManager"> <lookup-method name="createCommand" bean="myCommand"/> </bean>
-
还可以在实例方法上使用注解的方式进行方法修改,注解中填入的是返回内容的bean名称:
@Lookup("myCommand") protected abstract Command createCommand();
-
还可以单只使用@Lookup注解,Spring将根据bean标签配置的内容进行注入:
@Lookup protected abstract MyCommand createCommand();
任意方法替换
-
相比上文所述的抽象方法注入,任意方法的替换应用场景并不多。方法的替换即为将当前实例中的某方法替换为其他实例的方法。
-
使用replaced-method元素指定一个bean,替换现有的bean中方法的内容。
构建过程
-
首先存在一个需被修改的方法:
public class MyValueCalculator { public String computeValue(String input) {} }
-
创建一个实现了org.springframework.beans.factory.support.MethodReplacer接口的方法,并重写其中的reimplement方法,这个方法的参数可包含任意内容,返回任意类型,抛出任意错误:
public class ReplacementComputeValue implements MethodReplacer { public Object reimplement(Object o, Method m, Object[] args) throws Throwable { //进行处理并返回 return ...; } }
-
使用xml配置文件,将实例方法进行修改。arg-type中可以定义方法参数类型:
<bean id="myValueCalculator" class="x.y.z.MyValueCalculator"> <replaced-method name="computeValue" replacer="replacementComputeValue"> <arg-type>String</arg-type> </replaced-method> </bean> <bean id="replacementComputeValue" class="a.b.c.ReplacementComputeValue"/>