美文网首页
七、高级依赖关系配置

七、高级依赖关系配置

作者: 数独题 | 来源:发表于2017-03-05 11:00 被阅读6次

获取其他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配置文件中管理:

  • 项目升级、维护时经常需要改动的信息。
  • 控制项目类各组件耦合关系的代码。

相关文章

网友评论

      本文标题:七、高级依赖关系配置

      本文链接:https://www.haomeiwen.com/subject/quusgttx.html