七、高级依赖关系配置

获取其他Bean的属性值:

PropertyPathFactoryBean用来获取目标Bean的属相值(实际上就是它的getter方法的返回值),获得的值可以注入给其他Bean,也可以直接定义成新的Bean。
使用PropertyPathFactoryBean来调用其他Bean的getter方法需要指定如下信息:

  • 调用哪个对象。有PropertyPathFactoryBean的setTargetPbject(Object targetObject)方法指定。
  • 调用哪个getter方法。由PropertyPathFactoryBean的setPropertyPath(String propertyPath)方法指定。

beans.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"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd" >
    
      <!-- 定义一个将要被应用的目标Bean -->
      <bean id="persion" class="entity.Persion">
         <property name="age" value="30"/>
         <property name="son">
            <!-- 使用嵌套Bean定义setSon()方法的参数值 -->
            <bean class="entity.Son">
               <property name="age" value="11"/>
            </bean>
         </property>
      </bean>
      <!-- 将指定Bean实例的getter方法返回值定义成son1 Bean -->
      <bean id="son1" class="entity.Son1">
         <!--确定目标Bean,指定son1 Bean来自哪个Bean的getter方法 -->
         <property name="targetBeanName" value="persion"/>
         <!-- 指定son1 Bean来自目标Bean的那个getter方法,son代表getSon() -->
         <property name="propettyPath" value="son"/>
      </bean>
</beans>

SpringTest.java

public class SpringTest
{
    public static void main(String[] args)
    { 
         ApplicationContext ctx=new ClassPathXmlApplicationContext("beans.xml");
         System.out.println("系统获取son1:"ctx.getBean("son1"));
    }
}

输出

系统获取son1: Son[age=11]

获取Field值:

获取方法返回值:

Spring框架的本质就是通过XML配置来执行java代码,因此几乎可以把所有的Java代码放到Spring配置文件中管理:

  • 调用构造器创建对象(包括使用工厂方法创建对象),用<bean.../>元素。
  • 调用setter方法,用<property.../>元素。
  • 调用getter方法,PropertyPathFactoryBean或<util:property-path.../>元素。
  • 调用普通方法,用MethodInvokingFactoryBean工厂Bean。
  • 获取Field的值,用FieldRetrievingFactoryBean或<util:constant.../>元素。

一般来说,应该讲如下两类信息放到XML配置文件中管理:

  • 项目升级、维护时经常需要改动的信息。
  • 控制项目类各组件耦合关系的代码。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,850评论 19 139
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 32,514评论 18 399
  • 上篇文章我们对Spring做了初步的学习,了解了基本的依赖注入思想、学会简单的配置bean、能够使用Spring容...
    Single_YAM阅读 2,726评论 0 1
  • 金指尖的花园阅读 1,477评论 0 1
  • 一早起来陪老妈去医院,装动态血压检测机,由于出门时检查不仔细,忘带检查单,跑步的功力派上用场,奔袭往返,所幸未误事...
    自在飞花12388阅读 1,693评论 0 2

友情链接更多精彩内容