`
isiqi
  • 浏览: 16027889 次
  • 性别: Icon_minigender_1
  • 来自: 济南
社区版块
存档分类
最新评论

【第三章】 DI 之 3.3 更多DI的知识 ——跟我学spring3

 
阅读更多

3.3.1 延迟初始化Bean

延迟初始化也叫做惰性初始化,指不提前初始化Bean,而是只有在真正使用时才创建及初始化Bean。

配置方式很简单只需在<bean>标签上指定 “lazy-init” 属性值为“true”即可延迟初始化Bean。

Spring容器会在创建容器时提前初始化“singleton”作用域的Bean,“singleton”就是单例的意思即整个容器每个Bean只有一个实例,后边会详细介绍。Spring容器预先初始化Bean通常能帮助我们提前发现配置错误,所以如果没有什么情况建议开启,除非有某个Bean可能需要加载很大资源,而且很可能在整个应用程序生命周期中很可能使用不到,可以设置为延迟初始化。

延迟初始化的Bean通常会在第一次使用时被初始化;或者在被非延迟初始化Bean作为依赖对象注入时在会随着初始化该Bean时被初始化,因为在这时使用了延迟初始化Bean。

容器管理初始化Bean消除了编程实现延迟初始化,完全由容器控制,只需在需要延迟初始化的Bean定义上配置即可,比编程方式更简单,而且是无侵入代码的。

具体配置如下:


java代码:
  1. <beanid="helloApi"
  2. class="cn.javass.spring.chapter2.helloworld.HelloImpl"
  3. lazy-init="true"/>

3.3.2 使用depends-on

depends-on是指指定Bean初始化及销毁时的顺序,使用depends-on属性指定的Bean要先初始化完毕后才初始化当前Bean,由于只有“singleton”Bean能被Spring管理销毁,所以当指定的Bean都是“singleton”时,使用depends-on属性指定的Bean要在指定的Bean之后销毁。


java代码:
  1. 注:文档中说销毁Bean的顺序:Dependentbeansthatdefineadepends-onrelationshipwithagivenbeanaredestroyedfirst,priortothegivenbeanitselfbeingdestroyed.
  2. 意思是:在depends-on属性中定义的“依赖Bean”要在定义该属性的Bean之前销毁。
  3. 但实际是错误的,定义“depends-on”属性的Bean会首先被销毁,然后才是“depends-on”指定的Bean被销毁。大家可以试验一下。


配置方式如下:


java代码:
  1. <beanid="helloApi"class="cn.javass.spring.chapter2.helloworld.HelloImpl"/>
  2. <beanid="decorator"
  3. class="cn.javass.spring.chapter3.bean.HelloApiDecorator"
  4. depends-on="helloApi">
  5. <propertyname="helloApi"><refbean="helloApi"/></property>
  6. </bean>


“decorator”指定了“depends-on”属性为“helloApi”,所以在“decorator”Bean初始化之前要先初始化“helloApi”,而在销毁“helloApi”之前先要销毁“decorator”,大家注意一下销毁顺序,与文档上的不符。

“depends-on”属性可以指定多个Bean,若指定多个Bean可以用“;”、“,”、空格分割。

那“depends-on”有什么好处呢?主要是给出明确的初始化及销毁顺序,比如要初始化“decorator”时要确保“helloApi”Bean的资源准备好了,否则使用“decorator”时会看不到准备的资源;而在销毁时要先在“decorator”Bean的把对“helloApi”资源的引用释放掉才能销毁“helloApi”,否则可能销毁 “helloApi”时而“decorator”还保持着资源访问,造成资源不能释放或释放错误。


让我们看个例子吧,在平常开发中我们可能需要访问文件系统,而文件打开、关闭是必须配对的,不能打开后不关闭,从而造成其他程序不能访问该文件。让我们来看具体配置吧:


1)准备测试类:


ResourceBean从配置文件中配置文件位置,然后定义初始化方法init中打开指定的文件,然后获取文件流;最后定义销毁方法destroy用于在应用程序关闭时调用该方法关闭掉文件流。


DependentBean中会注入ResourceBean,并从ResourceBean中获取文件流写入内容;定义初始化方法init用来定义一些初始化操作并向文件中输出文件头信息;最后定义销毁方法用于在关闭应用程序时想文件中输出文件尾信息。


具体代码如下:



java代码:
  1. packagecn.javass.spring.chapter3.bean;
  2. importjava.io.File;
  3. importjava.io.FileNotFoundException;
  4. importjava.io.FileOutputStream;
  5. importjava.io.IOException;
  6. publicclassResourceBean{
  7. privateFileOutputStreamfos;
  8. privateFilefile;
  9. //初始化方法
  10. publicvoidinit(){
  11. System.out.println("ResourceBean:========初始化");
  12. //加载资源,在此只是演示
  13. System.out.println("ResourceBean:========加载资源,执行一些预操作");
  14. try{
  15. this.fos=newFileOutputStream(file);
  16. }catch(FileNotFoundExceptione){
  17. e.printStackTrace();
  18. }
  19. }
  20. //销毁资源方法
  21. publicvoiddestroy(){
  22. System.out.println("ResourceBean:========销毁");
  23. //释放资源
  24. System.out.println("ResourceBean:========释放资源,执行一些清理操作");
  25. try{
  26. fos.close();
  27. }catch(IOExceptione){
  28. e.printStackTrace();
  29. }
  30. }
  31. publicFileOutputStreamgetFos(){
  32. returnfos;
  33. }
  34. publicvoidsetFile(Filefile){
  35. this.file=file;
  36. }
  37. }



java代码:
  1. packagecn.javass.spring.chapter3.bean;
  2. importjava.io.IOException;
  3. publicclassDependentBean{
  4. ResourceBeanresourceBean;
  5. publicvoidwrite(Stringss)throwsIOException{
  6. System.out.println("DependentBean:=======写资源");
  7. resourceBean.getFos().write(ss.getBytes());
  8. }
  9. //初始化方法
  10. publicvoidinit()throwsIOException{
  11. System.out.println("DependentBean:=======初始化");
  12. resourceBean.getFos().write("DependentBean:=======初始化=====".getBytes());
  13. }
  14. //销毁方法
  15. publicvoiddestroy()throwsIOException{
  16. System.out.println("DependentBean:=======销毁");
  17. //在销毁之前需要往文件中写销毁内容
  18. resourceBean.getFos().write("DependentBean:=======销毁=====".getBytes());
  19. }
  20. publicvoidsetResourceBean(ResourceBeanresourceBean){
  21. this.resourceBean=resourceBean;
  22. }
  23. }


2)类定义好了,让我们来进行Bean定义吧,具体配置文件如下:


java代码:
  1. <beanid="resourceBean"
  2. class="cn.javass.spring.chapter3.bean.ResourceBean"
  3. init-method="init"destroy-method="destroy">
  4. <propertyname="file"value="D:/test.txt"/>
  5. </bean>
  6. <beanid="dependentBean"
  7. class="cn.javass.spring.chapter3.bean.DependentBean"
  8. init-method="init"destroy-method="destroy"depends-on="resourceBean">
  9. <propertyname="resourceBean"ref="resourceBean"/>
  10. </bean>


<property name="file" value="D:/test.txt"/>配置:Spring容器能自动把字符串转换为java.io.File。


init-method="init":指定初始化方法,在构造器注入和setter注入完毕后执行。

destroy-method="destroy":指定销毁方法,只有“singleton”作用域能销毁,“prototype”作用域的一定不能,其他作用域不一定能;后边再介绍。


在此配置中,dependentBean初始化在resourceBean之前被初始化,resourceBean销毁会在dependentBean销毁之后执行。

3)配置完毕,测试一下吧:


java代码:
  1. packagecn.javass.spring.chapter3;
  2. importjava.io.IOException;
  3. importorg.junit.Test;
  4. importorg.springframework.context.support.ClassPathXmlApplicationContext;
  5. importcn.javass.spring.chapter3.bean.DependentBean;
  6. publicclassMoreDependencyInjectTest{
  7. @Test
  8. publicvoidtestDependOn()throwsIOException{
  9. ClassPathXmlApplicationContextcontext=
  10. newClassPathXmlApplicationContext("chapter3/depends-on.xml");
  11. //一点要注册销毁回调,否则我们定义的销毁方法不执行
  12. context.registerShutdownHook();
  13. DependentBeandependentBean=
  14. context.getBean("dependentBean",DependentBean.class);
  15. dependentBean.write("aaa");
  16. }
  17. }


测试跟其他测试完全一样,只是在此我们一定要注册销毁方法回调,否则销毁方法不会执行。

如果配置没问题会有如下输出:


java代码:
  1. ResourceBean:========初始化
  2. ResourceBean:========加载资源,执行一些预操作
  3. DependentBean:=========初始化
  4. DependentBean:=========写资源
  5. DependentBean:=========销毁
  6. ResourceBean:========销毁
  7. ResourceBean:========释放资源,执行一些清理操作


3.3.3 自动装配

自动装配就是指由Spring来自动地注入依赖对象,无需人工参与。


目前Spring3.0支持“no”、“byName ”、“byType”、“constructor”四种自动装配,默认是“no”指不支持自动装配的,其中Spring3.0已不推荐使用之前版本的“autodetect”自动装配,推荐使用Java 5+支持的(@Autowired)注解方式代替;如果想支持“autodetect”自动装配,请将schema改为“spring-beans-2.5.xsd”或去掉。


自动装配的好处是减少构造器注入和setter注入配置,减少配置文件的长度。自动装配通过配置<bean>标签的“autowire”属性来改变自动装配方式。接下来让我们挨着看下配置的含义。


一、default:表示使用默认的自动装配,默认的自动装配需要在<beans>标签中使用default-autowire属性指定,其支持“no”、“byName ”、“byType”、“constructor”四种自动装配,如果需要覆盖默认自动装配,请继续往下看;


二、no:意思是不支持自动装配,必须明确指定依赖。


三、byName:通过设置Bean定义属性autowire="byName",意思是根据名字进行自动装配,只能用于setter注入。比如我们有方法“setHelloApi”,则“byName”方式Spring容器将查找名字为helloApi的Bean并注入,如果找不到指定的Bean,将什么也不注入。

例如如下Bean定义配置:


java代码:
  1. <beanid="helloApi"class="cn.javass.spring.chapter2.helloworld.HelloImpl"/>
  2. <beanid="bean"class="cn.javass.spring.chapter3.bean.HelloApiDecorator"
  3. autowire="byName"/>


测试代码如下:



java代码:
  1. packagecn.javass.spring.chapter3;
  2. importjava.io.IOException;
  3. importorg.junit.Test;
  4. importorg.springframework.context.support.ClassPathXmlApplicationContext;
  5. importcn.javass.spring.chapter2.helloworld.HelloApi;
  6. publicclassAutowireBeanTest{
  7. @Test
  8. publicvoidtestAutowireByName()throwsIOException{
  9. ClassPathXmlApplicationContextcontext=
  10. newClassPathXmlApplicationContext("chapter3/autowire-byName.xml");
  11. HelloApihelloApi=context.getBean("bean",HelloApi.class);
  12. helloApi.sayHello();
  13. }
  14. }


是不是不要配置<property>了,如果一个bean有很多setter注入,通过“byName”方式是不是能减少很多<property>配置。此处注意了,在根据名字注入时,将把当前Bean自己排除在外:比如“hello”Bean类定义了“setHello”方法,则hello是不能注入到“setHello”的。


四、“byType”:通过设置Bean定义属性autowire="byType",意思是指根据类型注入,用于setter注入,比如如果指定自动装配方式为“byType”,而“setHelloApi”方法需要注入HelloApi类型数据,则Spring容器将查找HelloApi类型数据,如果找到一个则注入该Bean,如果找不到将什么也不注入,如果找到多个Bean将优先注入<bean>标签“primary”属性为true的Bean,否则抛出异常来表明有个多个Bean发现但不知道使用哪个。让我们用例子来讲解一下这几种情况吧。


1)根据类型只找到一个Bean,此处注意了,在根据类型注入时,将把当前Bean自己排除在外,即如下配置中helloApi和bean都是HelloApi接口的实现,而“bean”通过类型进行注入“HelloApi”类型数据时自己是排除在外的,配置如下(具体测试请参考AutowireBeanTest.testAutowireByType1方法):


java代码:
  1. <beanclass="cn.javass.spring.chapter2.helloworld.HelloImpl"/>
  2. <beanid="bean"class="cn.javass.spring.chapter3.bean.HelloApiDecorator"
  3. autowire="byType"/>


2)根据类型找到多个Bean时,对于集合类型(如List、Set)将注入所有匹配的候选者,而对于其他类型遇到这种情况可能需要使用“autowire-candidate”属性为false来让指定的Bean放弃作为自动装配的候选者,或使用“primary”属性为true来指定某个Bean为首选Bean:

2.1)通过设置Bean定义的“autowire-candidate”属性为false来把指定Bean后自动装配候选者中移除:


java代码:
  1. <beanclass="cn.javass.spring.chapter2.helloworld.HelloImpl"/>
  2. <!--从自动装配候选者中去除-->
  3. <beanclass="cn.javass.spring.chapter2.helloworld.HelloImpl"
  4. autowire-candidate="false"/>
  5. <beanid="bean1"class="cn.javass.spring.chapter3.bean.HelloApiDecorator"
  6. autowire="byType"/>


2.2)通过设置Bean定义的“primary”属性为false来把指定自动装配时候选者中首选Bean:


java代码:
  1. <beanclass="cn.javass.spring.chapter2.helloworld.HelloImpl"/>
  2. <!--自动装配候选者中的首选Bean-->
  3. <beanclass="cn.javass.spring.chapter2.helloworld.HelloImpl"primary="true"/>
  4. <beanid="bean"class="cn.javass.spring.chapter3.bean.HelloApiDecorator"
  5. autowire="byType"/>


具体测试请参考AutowireBeanTest类的testAutowireByType***方法。


五、“constructor”:通过设置Bean定义属性autowire="constructor",功能和“byType”功能一样,根据类型注入构造器参数,只是用于构造器注入方式,直接看例子吧:


java代码:
  1. <beanclass="cn.javass.spring.chapter2.helloworld.HelloImpl"/>
  2. <!--自动装配候选者中的首选Bean-->
  3. <beanclass="cn.javass.spring.chapter2.helloworld.HelloImpl"primary="true"/>
  4. <beanid="bean"
  5. class="cn.javass.spring.chapter3.bean.HelloApiDecorator"
  6. autowire="constructor"/>


测试代码如下:


java代码:
  1. @Test
  2. publicvoidtestAutowireByConstructor()throwsIOException{
  3. ClassPathXmlApplicationContextcontext=
  4. newClassPathXmlApplicationContext("chapter3/autowire-byConstructor.xml");
  5. HelloApihelloApi=context.getBean("bean",HelloApi.class);
  6. helloApi.sayHello();
  7. }


六、autodetect:自动检测是使用“constructor”还是“byType”自动装配方式,已不推荐使用。如果Bean有空构造器那么将采用“byType”自动装配方式,否则使用“constructor”自动装配方式。此处要把3.0的xsd替换为2.5的xsd,否则会报错。


java代码:
  1. <?xmlversion="1.0"encoding="UTF-8"?>
  2. <beansxmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xsi:schemaLocation="
  6. http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
  8. http://www.springframework.org/schema/context
  9. http://www.springframework.org/schema/context/spring-context-2.5.xsd">
  10. <beanclass="cn.javass.spring.chapter2.helloworld.HelloImpl"/>
  11. <!--自动装配候选者中的首选Bean-->
  12. <beanclass="cn.javass.spring.chapter2.helloworld.HelloImpl"primary="true"/>
  13. <beanid="bean"
  14. class="cn.javass.spring.chapter3.bean.HelloApiDecorator"
  15. autowire="autodetect"/>
  16. </beans>


可以采用在“<beans>”标签中通过“default-autowire”属性指定全局的自动装配方式,即如果default-autowire=”byName”,将对所有Bean进行根据名字进行自动装配。

不是所有类型都能自动装配:

  • 不能自动装配的数据类型:Object、基本数据类型(Date、CharSequence、Number、URI、URL、Class、int)等;
  • 通过“<beans>”标签default-autowire-candidates属性指定的匹配模式,不匹配的将不能作为自动装配的候选者,例如指定“*Service,*Dao”,将只把匹配这些模式的Bean作为候选者,而不匹配的不会作为候选者;
  • 通过将“<bean>”标签的autowire-candidate属性可被设为false,从而该Bean将不会作为依赖注入的候选者。

数组、集合、字典类型的根据类型自动装配和普通类型的自动装配是有区别的:

  • 数组类型、集合(Set、Collection、List)接口类型:将根据泛型获取匹配的所有候选者并注入到数组或集合中,如“List<HelloApi> list”将选择所有的HelloApi类型Bean并注入到list中,而对于集合的具体类型将只选择一个候选者,“如 ArrayList<HelloApi> list”将选择一个类型为ArrayList的Bean注入,而不是选择所有的HelloApi类型Bean进行注入;
  • 字典(Map)接口类型:同样根据泛型信息注入,键必须为String类型的Bean名字,值根据泛型信息获取,如“Map<String, HelloApi> map” 将选择所有的HelloApi类型Bean并注入到map中,而对于具体字典类型如“HashMap<String, HelloApi> map”将只选择类型为HashMap的Bean注入,而不是选择所有的HelloApi类型Bean进行注入。


自动装配我们已经介绍完了,自动装配能带给我们什么好处呢?首先,自动装配确实减少了配置文件的量;其次, “byType”自动装配能在相应的Bean更改了字段类型时自动更新,即修改Bean类不需要修改配置,确实简单了。


自动装配也是有缺点的,最重要的缺点就是没有了配置,在查找注入错误时非常麻烦,还有比如基本类型没法完成自动装配,所以可能经常发生一些莫名其妙的错误,在此我推荐大家不要使用该方式,最好是指定明确的注入方式,或者采用最新的Java5+注解注入方式。所以大家在使用自动装配时应该考虑自己负责项目的复杂度来进行衡量是否选择自动装配方式。

自动装配注入方式能和配置注入方式一同工作吗?当然可以,大家只需记住配置注入的数据会覆盖自动装配注入的数据。

大家是否注意到对于采用自动装配方式时如果没找到合适的的Bean时什么也不做,这样在程序中总会莫名其妙的发生一些空指针异常,而且是在程序运行期间才能发现,有没有办法能在提前发现这些错误呢?接下来就让我来看下依赖检查吧。

3.3.4 依赖检查

上一节介绍的自动装配,很可能发生没有匹配的Bean进行自动装配,如果此种情况发生,只有在程序运行过程中发生了空指针异常才能发现错误,如果能提前发现该多好啊,这就是依赖检查的作用。


依赖检查:用于检查Bean定义的属性都注入数据了,不管是自动装配的还是配置方式注入的都能检查,如果没有注入数据将报错,从而提前发现注入错误,只检查具有setter方法的属性。

Spring3+也不推荐配置方式依赖检查了,建议采用Java5+ @Required注解方式,测试时请将XML schema降低为2.5版本的,和自动装配中“autodetect”配置方式的xsd一样。


java代码:
  1. <?xmlversion="1.0"encoding="UTF-8"?>
  2. <beansxmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="
  5. http://www.springframework.org/schema/beans
  6. http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
  7. </beans>


依赖检查有none、simple、object、all四种方式,接下来让我们详细介绍一下:


一、none:默认方式,表示不检查;


二、objects:检查除基本类型外的依赖对象,配置方式为:dependency-check="objects",此处我们为HelloApiDecorator添加一个String类型属性“message”,来测试如果有简单数据类型的属性为null,也不报错;


java代码:
  1. <beanid="helloApi"class="cn.javass.spring.chapter2.helloworld.HelloImpl"/>
  2. <!--注意我们没有注入helloApi,所以测试时会报错-->
  3. <beanid="bean"
  4. class="cn.javass.spring.chapter3.bean.HelloApiDecorator"
  5. dependency-check="objects">
  6. <propertyname="message"value="Haha"/>
  7. </bean>


注意由于我们没有注入bean需要的依赖“helloApi”,所以应该抛出异常UnsatisfiedDependencyException,表示没有发现满足的依赖:


java代码:
  1. packagecn.javass.spring.chapter3;
  2. importjava.io.IOException;
  3. importorg.junit.Test;
  4. importorg.springframework.beans.factory.UnsatisfiedDependencyException;
  5. importorg.springframework.context.support.ClassPathXmlApplicationContext;
  6. publicclassDependencyCheckTest{
  7. @Test(expected=UnsatisfiedDependencyException.class)
  8. publicvoidtestDependencyCheckByObject()throwsIOException{
  9. //将抛出异常
  10. newClassPathXmlApplicationContext("chapter3/dependency-check-object.xml");
  11. }
  12. }


三、simple:对基本类型进行依赖检查,包括数组类型,其他依赖不报错;配置方式为:dependency-check="simple",以下配置中没有注入message属性,所以会抛出异常:


java代码:
  1. <beanid="helloApi"class="cn.javass.spring.chapter2.helloworld.HelloImpl"/>
  2. <!--注意我们没有注入message属性,所以测试时会报错-->
  3. <beanid="bean"
  4. class="cn.javass.spring.chapter3.bean.HelloApiDecorator"
  5. dependency-check="simple">
  6. <propertyname="helloApi"ref="helloApi"/>
  7. </bean>


四、all:对所以类型进行依赖检查,配置方式为:dependency-check="all",如下配置方式中如果两个属性其中一个没配置将报错。


java代码:
  1. <beanid="helloApi"class="cn.javass.spring.chapter2.helloworld.HelloImpl"/>
  2. <beanid="bean"
  3. class="cn.javass.spring.chapter3.bean.HelloApiDecorator"
  4. dependency-check="all">
  5. <propertyname="helloApi"ref="helloApi"/>
  6. <propertyname="message"value="Haha"/>
  7. </bean>


依赖检查也可以通过“<beans>”标签中default-dependency-check属性来指定全局依赖检查配置。

3.3.5方法注入

所谓方法注入其实就是通过配置方式覆盖或拦截指定的方法,通常通过代理模式实现。Spring提供两种方法注入:查找方法注入和方法替换注入。

因为Spring是通过CGLIB动态代理方式实现方法注入,也就是通过动态修改类的字节码来实现的,本质就是生成需方法注入的类的子类方式实现。

在进行测试之前,我们需要确保将“com.springsource.cn.sf.cglib-2.2.0.jar”放到lib里并添加到“Java Build Path”中的Libararies中。否则报错,异常中包含“nested exception is java.lang.NoClassDefFoundError: cn/sf/cglib/proxy/CallbackFilter”

传统方式和Spring容器管理方式唯一不同的是不需要我们手动生成子类,而是通过配置方式来实现;其中如果要替换createPrinter()方法的返回值就使用查找方法注入;如果想完全替换sayHello()方法体就使用方法替换注入。 接下来让我们看看具体实现吧。


一、查找方法注入:又称为Lookup方法注入,用于注入方法返回结果,也就是说能通过配置方式替换方法返回结果。使用<lookup-method name="方法名" bean="bean名字"/>配置;其中name属性指定方法名,bean属性指定方法需返回的Bean。

方法定义格式:访问级别必须是public或protected,保证能被子类重载,可以是抽象方法,必须有返回值,必须是无参数方法,查找方法的类和被重载的方法必须为非final:

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


因为“singleton”Bean在容器中只有一个实例,而“prototype”Bean是每次获取容器都返回一个全新的实例,所以如果“singleton”Bean在使用“prototype” Bean情况时,那么“prototype”Bean由于是“singleton”Bean的一个字段属性,所以获取的这个“prototype”Bean就和它所在的“singleton”Bean具有同样的生命周期,所以不是我们所期待的结果。因此查找方法注入就是用于解决这个问题。


1) 首先定义我们需要的类,Printer类是一个有状态的类,counter字段记录访问次数:


java代码:
  1. packagecn.javass.spring.chapter3.bean;
  2. publicclassPrinter{
  3. privateintcounter=0;
  4. publicvoidprint(Stringtype){
  5. System.out.println(type+"printer:"+counter++);
  6. }
  7. }


HelloImpl5类用于打印欢迎信息,其中包括setter注入和方法注入,此处特别需要注意的是该类是抽象的,充分说明了需要容器对其进行子类化处理,还定义了一个抽象方法createPrototypePrinter用于创建“prototype”Bean,createSingletonPrinter方法用于创建“singleton”Bean,此处注意方法会被Spring拦截,不会执行方法体代码:


java代码:
  1. packagecn.javass.spring.chapter3;
  2. importcn.javass.spring.chapter2.helloworld.HelloApi;
  3. importcn.javass.spring.chapter3.bean.Printer;
  4. publicabstractclassHelloImpl5implementsHelloApi{
  5. privatePrinterprinter;
  6. publicvoidsayHello(){
  7. printer.print("setter");
  8. createPrototypePrinter().print("prototype");
  9. }
  10. publicabstractPrintercreatePrototypePrinter();
  11. publicPrintercreateSingletonPrinter(){
  12. System.out.println("该方法不会被执行,如果输出就错了");
  13. returnnewPrinter();
  14. }
  15. publicvoidsetPrinter(Printerprinter){
  16. this.printer=printer;
  17. }
  18. }


2) 开始配置了,配置文件在(resources/chapter3/lookupMethodInject.xml),其中“prototypePrinter”是“prototype”Printer,“singletonPrinter”是“singleton”Printer,“helloApi1”是“singleton”Bean,而“helloApi2”注入了“prototype”Bean:


java代码:
  1. <beanid="prototypePrinter"
  2. class="cn.javass.spring.chapter3.bean.Printer"scope="prototype"/>
  3. <beanid="singletonPrinter"
  4. class="cn.javass.spring.chapter3.bean.Printer"scope="singleton"/>
  5. <beanid="helloApi1"class="cn.javass.spring.chapter3.HelloImpl5"scope="singleton">
  6. <propertyname="printer"ref="prototypePrinter"/>
  7. <lookup-methodname="createPrototypePrinter"bean="prototypePrinter"/>
  8. <lookup-methodname="createSingletonPrinter"bean="singletonPrinter"/>
  9. </bean>
  10. <beanid="helloApi2"class="cn.javass.spring.chapter3.HelloImpl5"scope="prototype">
  11. <propertyname="printer"ref="prototypePrinter"/>
  12. <lookup-methodname="createPrototypePrinter"bean="prototypePrinter"/>
  13. <lookup-methodname="createSingletonPrinter"bean="singletonPrinter"/>
  14. </bean>


3)测试代码如下:


java代码:
  1. packagecn.javass.spring.chapter3;
  2. importorg.junit.Test;
  3. importorg.springframework.context.support.ClassPathXmlApplicationContext;
  4. importcn.javass.spring.chapter2.helloworld.HelloApi;
  5. publicclassMethodInjectTest{
  6. @Test
  7. publicvoidtestLookup(){
  8. ClassPathXmlApplicationContextcontext=
  9. newClassPathXmlApplicationContext("chapter3/lookupMethodInject.xml");
  10. System.out.println("=======singletonsayHello======");
  11. HelloApihelloApi1=context.getBean("helloApi1",HelloApi.class);
  12. helloApi1.sayHello();
  13. helloApi1=context.getBean("helloApi1",HelloApi.class);
  14. helloApi1.sayHello();
  15. System.out.println("=======prototypesayHello======");
  16. HelloApihelloApi2=context.getBean("helloApi2",HelloApi.class);
  17. helloApi2.sayHello();
  18. helloApi2=context.getBean("helloApi2",HelloApi.class);
  19. helloApi2.sayHello();
  20. }}


其中“helloApi1”测试中,其输出结果如下:


java代码:
  1. =======singletonsayHello======
  2. setterprinter:0
  3. prototypeprinter:0
  4. singletonprinter:0
  5. setterprinter:1
  6. prototypeprinter:0
  7. singletonprinter:1


首先“helloApi1”是“singleton”,通过setter注入的“printer”是“prototypePrinter”,所以它应该输出“setter printer:0”和“setter printer:1”;而“createPrototypePrinter”方法注入了“prototypePrinter”,所以应该输出两次“prototype printer:0”;而“createSingletonPrinter”注入了“singletonPrinter”,所以应该输出“singleton printer:0”和“singleton printer:1”。

而“helloApi2”测试中,其输出结果如下:


java代码:
  1. =======prototypesayHello======
  2. setterprinter:0
  3. prototypeprinter:0
  4. singletonprinter:2
  5. setterprinter:0
  6. prototypeprinter:0
  7. singletonprinter:3


首先“helloApi2”是“prototype”,通过setter注入的“printer”是“prototypePrinter”,所以它应该输出两次“setter printer:0”;而“createPrototypePrinter”方法注入了“prototypePrinter”,所以应该输出两次“prototype printer:0”;而“createSingletonPrinter”注入了“singletonPrinter”,所以应该输出“singleton printer:2”和“singleton printer:3”。

大家是否注意到“createSingletonPrinter”方法应该输出“该方法不会被执行,如果输出就错了”,而实际是没输出的,这说明Spring拦截了该方法并使用注入的Bean替换了返回结果。

方法注入主要用于处理“singleton”作用域的Bean需要其他作用域的Bean时,采用Spring查找方法注入方式无需修改任何代码即能获取需要的其他作用域的Bean。


二、替换方法注入:也叫“MethodReplacer”注入,和查找注入方法不一样的是,他主要用来替换方法体。通过首先定义一个MethodReplacer接口实现,然后如下配置来实现:


java代码:
  1. <replaced-methodname="方法名"replacer="MethodReplacer实现">
  2. <arg-type>参数类型</arg-type>
  3. </replaced-method>”

1)首先定义MethodReplacer实现,完全替换掉被替换方法的方法体及返回值,其中reimplement方法重定义方法 功能,参数obj为被替换方法的对象,method为被替换方法,args为方法参数;最需要注意的是不能再 通过“method.invoke(obj, new String[]{"hehe"});” 反射形式再去调用原来方法,这样会产生循环调用;如果返回值类型为Void,请在实现中返回null:


java代码:
  1. packagecn.javass.spring.chapter3.bean;
  2. importjava.lang.reflect.Method;
  3. importorg.springframework.beans.factory.support.MethodReplacer;
  4. publicclassPrinterReplacerimplementsMethodReplacer{
  5. @Override
  6. publicObjectreimplement(Objectobj,Methodmethod,Object[]args)throwsThrowable{
  7. System.out.println("PrintReplacer");
  8. //注意此处不能再通过反射调用了,否则会产生循环调用,知道内存溢出
  9. //method.invoke(obj,newString[]{"hehe"});
  10. returnnull;
  11. }
  12. }


2)配置如下,首先定义MethodReplacer实现,使用< replaced-method >标签来指定要进行替换方法,属性name指定替换的方法名字,replacer指定该方法的重新实现者,子标签< arg-type >用来指定原来方法参数的类型,必须指定否则找不到原方法:


java代码:
  1. <beanid="replacer"class="cn.javass.spring.chapter3.bean.PrinterReplacer"/>
  2. <beanid="printer"class="cn.javass.spring.chapter3.bean.Printer">
  3. <replaced-methodname="print"replacer="replacer">
  4. <arg-type>java.lang.String</arg-type>
  5. </replaced-method>
  6. </bean>


3)测试代码将输出“Print Replacer ”,说明方法体确实被替换了:


java代码:
  1. @Test
  2. publicvoidtestMethodReplacer(){
  3. ClassPathXmlApplicationContextcontext=newClassPathXmlApplicationContext("chapter3/methodReplacerInject.xml");
  4. Printerprinter=context.getBean("printer",Printer.class);
  5. printer.print("我将被替换");
  6. }
分享到:
评论

相关推荐

    跟我学spring3(1-7)

    【第三章】 DI 之 3.3 更多DI的知识 ——跟我学spring3 【第三章】 DI 之 3.4 Bean的作用域 ——跟我学spring3 【第四章】 资源 之 4.1 基础知识 ——跟我学spring3 【第四章】 资源 之 4.2 内置Resource实现 ——跟...

    跟开涛学Spring

    1.8 【第三章】 DI 之 3.3 更多DI的知识 ——跟我学spring3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .104 1.9 【第三章】 DI 之 3.4 Bean的作用域 ——跟我学spring3 . . . . . . . . . ...

    跟我学Spring3(3.3)更多的DI知识Java开发J

    跟我学Spring3(3.3)更多的DI知识Java开发Java经验技巧共20页.pdf.zip

    跟我学spring3(1-7).pdf

    Spring概述2.1 IoC基础2.2 IoC 容器基本原理2.3 IoC的配置使用——跟我学Spring33.1 DI的配置使用3.2 循环依赖3.3 更多DI的知识 3.4 Bean的作用域 4.1 基础知识4.2 内置Resource实现4.3 访问Resource4.4 Resource...

    跟我学Spring系列1

    【第二章】 IoC 之 2.2 IoC 容器基本原理 ——跟我学【第二章】 IoC 之 2.3 IoC的配置使用——跟我学Spring3【第三章】 DI 之 3

    跟我学spring3 .pdf

    详细讲解了 IOC DI AOP JDBC MVC 等等spring知识,有很高的学习价值

    SPRING DI注入例子

    SPRING DI注入例子 jar包没有包含

    SpringDI.rar

    Spring依赖注入(DI)的例子,包括接口注入、构造注入、set注入的简单类型和复杂类型注入的例子。

    springIOC和DI

    什么是spring,spring核心,spring优点,spring体系结构, 入门案例,DI基础,核心API,文档内附代码

    java Spring DI依赖注入.rar

    java Spring DI依赖注入.rar

    跟我学spring3(8-13).pdf

    spring3基础知识 IoC DI Spring表达式 SpEL Spring JDBC支持 Spring ORM集成 Spring与其他web框架集成 Spring注解零配置 Spring单元测试与集成测试

    Spring——IOC(控制反转)与DI(依赖注入).docx

    控制反转后将对象的创建转移给第三方; 控制反转是一种 通过描述XML(或注解) 并 通过第三方去生产或获取特定对象 的方式。 在Spring中实现控制反转的是IOC容器 ,其 实现方法是依赖注入 (Dependency ...

    casadi说明文档简介

    第三章:介绍符号【数据类型】、数据类型详解与基本操作 第四章:目标函数的定义与使用规范。以及casadi可以求解的问题类型。 第五章:casadi的数值评估通常在虚拟机进行,为加快估算时间可以将函数对象的子集进行c...

    spring杂谈 作者zhang KaiTao

    1. spring杂谈[原创] 1.1 Spring事务处理时自我调用的解决方案及一些实现方式的风险 ...1.32 Spring3 Web MVC下的数据类型转换(第一篇)——《跟我学Spring3 Web MVC》抢先看 1.33 Spring 注入集合类型

    Spring从入门到入土——依赖注入(DI)

    DIDependency Injection概念注入方式...Spring从入门到入土——依赖注入(DI) Spring从入门到入土——Bean的作用域 Dependency Injection 概念 依赖注入(DI) 依赖:指Bean对象的创建依赖于容器。Bean对象的依赖资

    Spring-DI时序图.png

    Spring Ioc DI 时序图分享给大家,希望对大家看源码有所帮助,不足之处欢迎批评指正,可以在下方留言

    spring入门学习-2、IOC、DI知识.pdf

    spring入门学习-2、IOC、DI知识.pdf

    Spring——DI和通过注解实现IOC和DI

    DI(依赖注入) – 问题的提出: 之前所说的IOC,其中没有提到,如果当spring保存的类中有其他属性需要赋值的话怎么办(其实可以用工厂模式来完成),所以今天我们就来解决这个问题。 – DI的概念: 当spring容器...

    多功能无线路由器——D-Link DI-724UP+A.pdf

    多功能无线路由器——D-Link DI-724UP+A.pdf

    spring培训-笔记

    重构第三步——工厂(Factory)模式的改进 10 重构第四步-IoC容器 11 控制反转(IoC)/依赖注入(DI) 11 什么是控制反转/依赖注入? 11 依赖注入的三种实现形式 12 BeanFactory 14 BeanFactory管理Bean...

Global site tag (gtag.js) - Google Analytics