实验:依赖注入之构造器注入_构造器


个人名片:

实验:依赖注入之构造器注入_notepad++_02


🐼作者简介:一名大三在校生,喜欢AI编程🎋
🐻❄️个人主页🥇:落798. 🐼

  • RabbitMQ快速入门🔥 🐓每日一句:🍭我很忙,但我要忙的有意义!
    欢迎评论 💬点赞👍🏻 收藏 📂加关注+



文章目录

  • 回顾:
  • 实验三:依赖注入之构造器注入
  • 写在后面🔥🔥🔥:
  • 欢迎添加微信,加入我的核心小队,请备注来意



回顾:

依赖注入(Dependency Injection,简称DI)是一种软件设计模式,它实现了控制反转(Inversion of Control,简称IoC)的原则,用于减少代码间的耦合。在依赖注入中,对象的依赖关系不是由对象本身在内部创建或查找,而是由外部容器或框架在创建对象时注入。构造器注入是依赖注入的一种形式,它通过对象的构造器(构造函数)来注入依赖。

实验三:依赖注入之构造器注入

①在Student类中添加有参构造

public Student(Integer id, String name, Integer age, String sex) {
    this.id = id;
    this.name = name;
    this.age = age;
    this.sex = sex;
}

②配置bean

spring-di.xml

<bean id="studentTwo" class="com.atguigu.spring6.bean.Student">
    <constructor-arg value="1002"></constructor-arg>
    <constructor-arg value="李四"></constructor-arg>
    <constructor-arg value="33"></constructor-arg>
    <constructor-arg value="女"></constructor-arg>
</bean>

注意:

constructor-arg标签还有两个属性可以进一步描述构造器参数:

  • index属性:指定参数所在位置的索引(从0开始)
  • name属性:指定参数名

③测试

@Test
public void testDIByConstructor(){
    ApplicationContext ac = new ClassPathXmlApplicationContext("spring-di.xml");
    Student studentOne = ac.getBean("studentTwo", Student.class);
    System.out.println(studentOne);
}

写在后面🔥🔥🔥:

本专栏是自己深入学习并结合Spring技术内幕一经典图书内容做出的的心得与总结,将其精简编写成一篇专栏供大家学习,希望对新学习Spring框架技术的小伙伴有所帮助。

图书推荐

实验:依赖注入之构造器注入_spring_03