zoukankan      html  css  js  c++  java
  • Spring 基于set方法的依赖注入

    注意,再次强调,注入一个值用value,注入一个引用,要使用    ref   来注入

     同时,注入的对象,要有set和get方法,才能通过方法注入。

    <?xml version="1.0" encoding="UTF-8"?>
    
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    
       <!-- Definition for textEditor bean -->
       <bean id="textEditor" class="com.tutorialspoint.TextEditor">
          <property name="spellChecker" ref="spellChecker"/>
       </bean>
    
       <!-- Definition for spellChecker bean -->
       <bean id="spellChecker" class="com.tutorialspoint.SpellChecker">
       </bean>
    
    </beans>

    使用 p-namespace 实现 XML 配置:

    如果你有许多的设值函数方法,那么在 XML 配置文件中使用 p-namespace 是非常方便的。让我们查看一下区别:

    以带有 标签的标准 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"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    
       <bean id="john-classic" class="com.example.Person">
          <property name="name" value="John Doe"/>
          <property name="spouse" ref="jane"/>
       </bean>
    
       <bean name="jane" class="com.example.Person">
          <property name="name" value="John Doe"/>
       </bean>
    
    </beans>

    上述 XML 配置文件可以使用 p-namespace 以一种更简洁的方式重写,如下所示:

    <?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:p="http://www.springframework.org/schema/p"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    
       <bean id="john-classic" class="com.example.Person"
          p:name="John Doe"
          p:spouse-ref="jane"/>
       </bean>
    
       <bean name="jane" class="com.example.Person"
          p:name="John Doe"/>
       </bean>
    
    </beans>

    在这里,你不应该区别指定原始值和带有 p-namespace 的对象引用。-ref 部分表明这不是一个直接的值,而是对另一个 bean 的引用。

  • 相关阅读:
    优雅的使用Python之软件管理
    优雅的使用python之环境管理
    SpriteSheet精灵动画引擎
    【译】AS3利用CPU缓存
    走在网页游戏开发的路上(十一)
    自定义路径创建Cocos2d-x项目
    C++静态库与动态库
    C++对象模型
    超时空英雄传说2复仇魔神完全攻略&秘技
    从头写个http client(java)
  • 原文地址:https://www.cnblogs.com/qie-zi/p/8795457.html
Copyright © 2011-2022 走看看