• 依赖注入DI(其实就是对象的创建和对象的属性赋值交给容器)


    (1)普通类型注入  value注入

    有一个类Student:

    1. public class Student
    2. {
    3. private String name;
    4. }
    5. //注意:使用setter注入(1)需要有相应的set方法的,比如setName,setAge方法
    6. // (2)需要有无参的构造方法
    7. //这里为了简化,没有写这个类的setName方法和无参构造方法

    在beans.xml文件中:(创建一个Student对象,并且给它的name这个属性赋值)

    1. //new一个对象叫作student,它来自Student类
    2. <bean id="student" class="com.kuang.pojo.Student">
    3. //给这个对象student的name属性赋值
    4. <property name="name" value="欧阳水鸣">property>
    5. bean>

     测试:

    1. //创建出beans.xml文件里面的所有bean,这些bean放到spring这个容器里面进行管理
    2. ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");
    3. //拿到这个叫做hello的bean
    4. Student student= (Student) context.getBean("student");
    5. System.out.println(student.getName());

    (2)引用类型注入  ref注入

    此时属性是一个对象,也就是说,一个类的对象是另一个类的属性

    step1:先创建一个类B

    1. public class B
    2. {
    3. private int height;
    4. }

    step2:再创建一个类A,类B的对象b是类A的属性

    1. public class A
    2. {
    3. private B b;
    4. }
    5. //完整的话这里也应该有set方法和无参构造方法:
    6. public class A
    7. {
    8. private B b;
    9. //set方法
    10. public void setB(B b)
    11. {
    12. this.b=b;
    13. }
    14. //无参构造方法
    15. public void A
    16. {
    17. system.out.println("类A的无参构造方法.......");
    18. }
    19. }

    step3:beans.xml这个文件中进行创建对象,给对象赋值

    1. //创建三个B类的对象b1,b2,b3
    2. <bean id="b1" class="com.kuang.pojo.B">
    3. <property name="height" value="123">property>
    4. bean>
    5. <bean id="b2" class="com.kuang.pojo.B">
    6. <property name="height" value="456">property>
    7. bean>
    8. <bean id="b3" class="com.kuang.pojo.B">
    9. <property name="height" value="789">property>
    10. bean>
    11. //创建两个A类的对象a1和a2,a1对象有b属性,a2对象也有b属性
    12. //给a1这个对象的b属性赋值b1
    13. <bean id="a1" class="com.kuang.pojo.A">
    14. <property name="b" ref="b1">property>
    15. bean>
    16. //给a2这个对象的b属性赋值b2
    17. <bean id="a2" class="com.kuang.pojo.A">
    18. <property name="b" ref="b2">property>
    19. bean>

    step4:测试类

    1. public class MyTest
    2. {
    3. public static void main(String[] args)
    4. {
    5. //创建出beans.xml文件里面的所有bean,这些bean放到spring这个容器里面进行管理
    6. ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");
    7. //拿到a1和a2两个bean
    8. A a1= (A) context.getBean("a1");
    9. A a2= (A) context.getBean("a2");
    10. System.out.println(a1.b.height);//123
    11. System.out.println(a2.b.height);//456
    12. }
    13. }

  • 相关阅读:
    系统移植开发阶段部署
    C#算法之冒泡排序算法
    Python之猜数字游戏
    详谈动态规划问题并解最大子数组和
    算术优化算法(Matlab代码实现)
    FPGA - ZYNQ Cache一致性问题
    【广州华锐互动】VR建筑施工事故体验:提高工人安全意识和责任感
    芋道前后端分离项目跳过登录
    互联网相关概念——RFC
    实用调试技巧
  • 原文地址:https://blog.csdn.net/weixin_47414034/article/details/126638814