侧边栏壁纸
  • 累计撰写 101 篇文章
  • 累计创建 89 个标签
  • 累计收到 9 条评论

spring系列笔记 - 第六章 构造注⼊

bearjun
2020-11-20 / 0 评论 / 0 点赞 / 1,450 阅读 / 1,331 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2020-11-20,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。
  • 注入:通过Spring的配置文件,为成员变量赋值

  • Set注入:Spring调用Set方法,通过配置文件,为成员变量赋值

  • 构造注入:Spring调用构造方法,通过配置文件,为成员变量赋值

1. 开发步骤

  • 为对象提供有参构造方法
public class Customer {
    private String name;
    private int age;

    public Customer(String name, int age) {
        this.name = name;
        this.age = age;
    }
}
  • spring配置文件设置
<bean id="customer" class="com.bearjun.entity.Customer">
    <constructor-arg>
        <!--对应的是name-->
        <value>zhenyu</value>
    </constructor-arg>
    <constructor-arg>
        <!--对应的是age-->
        <value>21</value>
    </constructor-arg>
</bean>

注意:的个数和顺序都要和实体的构造方法的个数和顺序保持一致。

2. 构造方法重载

2.1 参数个数不同时

参数个数不同时,通过控制 <constructor-arg> 标签的数量进⾏区分。

public class Customer {
    private String name;
    private int age;

    public Customer(String name, int age) {
        this.name = name;
        this.age = age;
    }
 
    public Customer(String name) {
        this.name = name;
    }

    public Customer(int age) {
        this.age = age;
    }
}
<bean id="customer" class="com.bearjun.entity.Customer">
    <constructor-arg>
        <value>bearjun</value>
    </constructor-arg>
</bean>
2.2 构造参数个数相同时

构造参数个数相同时,通过在标签引入 type 属性 进⾏类型的区分 <constructor-arg type="">

<bean id="customer" class="com.bearjun.entity.Customer">
    <constructor-arg type="int">
	<value>20</value>
    </constructor-arg>
</bean>

3. 注⼊的总结

未来的实战中,应用set注入还是构造注入?

答案:set注入更多
1、构造注入麻烦 (重载)
2、Spring框架底层 大量应用了set注入

20200521235846480.png

0

评论区