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 的引用。

  • 相关阅读:
    【题解】国家集训队礼物(Lucas定理)
    【题解】佳佳的斐波那契数列(矩阵)
    【题解】Zap(莫比乌斯反演)
    HNOI2019爆零记
    Emacs配置
    【题解】Journeys(线段树优化连边)
    一直没有敢发的NOIP2018游记
    【题解】Digit Tree
    【题解】BZOJ3489 A Hard RMQ problem(主席树套主席树)
    【题解】大括号
  • 原文地址:https://www.cnblogs.com/qie-zi/p/8795457.html
Copyright © 2011-2022 走看看