zoukankan      html  css  js  c++  java
  • 【Spring学习笔记-2.1】Spring的设值注入和构造注入

    设值注入:
    先通过无参数的构造函数创建一个Bean实例,然后调用对应的setter方法注入依赖关系;
    配置文件:

    1. <?xml version="1.0" encoding="GBK"?>
    2. <!-- Spring配置文件的根元素,使用spring-beans-4.0.xsd语义约束 -->
    3. <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xmlns="http://www.springframework.org/schema/beans"
    5. xsi:schemaLocation="http://www.springframework.org/schema/beans
    6. http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
    7. <bean id="chinese" class="org.crazyit.app.service.impl.Chinese">
    8. <property name="axe" ref="steelAxe"/>
    9. <property name="Stuname" value="zhangsan"/>
    10. </bean>
    11. <bean id="stoneAxe" class="org.crazyit.app.service.impl.StoneAxe"/>
    12. <bean id="steelAxe" class="org.crazyit.app.service.impl.SteelAxe"/>
    13. </beans>



    构造注入:
    直接调用有参数的构造器,当bean实例创建完成后,已经完成了依赖关系的注入;
    配置文件

    1. <?xml version="1.0" encoding="GBK"?>
    2. <!-- Spring配置文件的根元素,使用spring-beans-4.0.xsd语义约束 -->
    3. <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xmlns="http://www.springframework.org/schema/beans"
    5. xsi:schemaLocation="http://www.springframework.org/schema/beans
    6. http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
    7. <bean id="chinese" class="org.crazyit.app.service.impl.Chinese">
    8. <constructor-arg ref="steelAxe" type="org.crazyit.app.service.Axe"/>
    9. <constructor-arg value="zhangsan" type="String"/>
    10. </bean>
    11. <bean id="stoneAxe" class="org.crazyit.app.service.impl.StoneAxe"/>
    12. <bean id="steelAxe" class="org.crazyit.app.service.impl.SteelAxe"/>
    13. </beans>

    比较:
    建议使用 设值注入;
    对于依赖关系无需变化的注入,尽量采用构造注入;而其他依赖关系的注入,则优先考虑设值注入;





  • 相关阅读:
    语音识别算法阅读之CTC
    语音识别模型阅读之CLDNN
    声纹识别算法阅读之self-attentive x-vector
    Git链接两个远程仓库
    tortoisegit提交不到远程库问题解决记录
    安装 Git 命令之后,本地的工作区中的文件没有小图标解决办法
    .NET CLS(Common Language System)简介
    .NET CTS(Common Type System)简介
    C# 中间语言
    .NET 程序执行流程
  • 原文地址:https://www.cnblogs.com/ssslinppp/p/4372205.html
Copyright © 2011-2022 走看看