6

Spring-依赖注入

 2 years ago
source link: https://segmentfault.com/a/1190000041361593
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

构造器注入

引用 之前的文章

set方法注入

  1. 普通值注入,value
    pojo.java

    private String name;

    beans.xml

    <property name="name" value="向日葵"/>
  2. Bean注入,ref
    pojo.java

    private Address address;

    beans.xml

    <property name="address" ref="address"/>
  3. 数组注入
    pojo.java

    private String[] books;

    beans.xml

    <property name="books">
     <array>
         <value>红楼梦</value>
         <value>水浒传</value>
         <value>三国演义</value>
     </array>
    </property>
  4. List注入
    pojo.java

    private List<String> hobbies;

    beans.xml

    <property name="hobbies">
     <list>
         <value>听歌</value>
         <value>敲代码</value>
         <value>看电影</value>
     </list>
    </property>
  5. Map注入
    pojo.java

    private Map<String,String> card;

    beans.xml

    <property name="card">
     <map>
         <entry key="身份证" value="111111111111"/>
         <entry key="银行卡" value="222222222222"/>
     </map>
    </property>
  6. Set注入
    pojo.java

    private Set<String> games;

    beans.xml

    <property name="games">
     <set>
         <value>LOL</value>
         <value>COC</value>
         <value>BOB</value>
     </set>
    </property>
  7. null注入
    pojo.java

    private String wife;

    beans.xml

    <property name="wife">
     <null/>
    </property>
  8. Properties注入
    pojo.java

    private Properties info;

    beans.xml

    <property name="info">
     <props>
         <prop key="学号">20220201</prop>
         <prop key="性别">男</prop>
         <prop key="姓名">向日葵</prop>
     </props>
    </property>

拓展方式注入

  1. p命名空间注入
    相当于property注入

    <!--p命名空间注入,可以直接注入属性的值:property-->
    <bean id="user" class="com.sunfl.pojo.User" p:name="向日葵" p:age="18"/>
  2. c命名空间注入
    相当于构造器注入

    <!--c命名空间注入,通过构造器注入,construct-args-->
    <bean id="user2" class="com.sunfl.pojo.User" c:age="28" c:name="向日葵2"/>

注意:p命名空间和c命名空间不能直接使用,需要导入xml约束!

xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK