package com.example.pojo03;public class School { private String name; private String address; @Override public String toString() { return "School{" + "name='" + name + '\'' + ", address='" + address + '\'' + '}'; } public School(String name, String address) { this.name = name; this.address = address; System.out.println("School有参构造方法执行,实例对象被创建...."); }}
<?xml version="1.0" encoding="UTF-8"?>
package com.example.test;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class TestConstructor { //测试:通过构造方法的参数名称注入 @Test public void testConstructorArgs(){ //创建Spring容器 ApplicationContext ac = new ClassPathXmlApplicationContext("source03/applicationContext.xml"); //取出School对象并打印输出 System.out.printf("School实例对象: " + ac.getBean("school")); }}
School有参构造方法执行,实例对象被创建....School实例对象: School{name='nefu', address='哈尔滨'}Process finished with exit code 0
package com.example.pojo03;public class Student { private String name; private int age; private School school; @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + ", school=" + school + '}'; } public Student(String name, int age, School school) { this.name = name; this.age = age; this.school = school; System.out.println("Student有参构造方法执行,实例对象被创建...."); }}
//测试:通过构造方法的参数下标注入 @Test public void testConstructorIndex(){ //创建Spring容器 ApplicationContext ac = new ClassPathXmlApplicationContext("source03/applicationContext.xml"); //取出Student对象并打印输出 System.out.printf("Student实例对象: " + ac.getBean("student")); }
School有参构造方法执行,实例对象被创建....Student有参构造方法执行,实例对象被创建....Student实例对象: Student{name='荷包蛋', age=20, school=School{name='nefu', address='哈尔滨'}}Process finished with exit code 0
//测试:通过构造方法默认参数顺序注入 @Test public void testConstructorDefaultOrder(){ //创建Spring容器 ApplicationContext ac = new ClassPathXmlApplicationContext("source03/applicationContext.xml"); //取出Student对象并打印输出 System.out.printf("Student实例对象: " + ac.getBean("student02")); }
School有参构造方法执行,实例对象被创建....Student有参构造方法执行,实例对象被创建....Student实例对象: Student{name='荷包蛋', age=20, school=School{name='nefu', address='哈尔滨'}}Process finished with exit code 0
前两种注入方式,由于一种依靠参数名和待注入值绑定,一种依靠参数下标和待注入值绑定,做到了注入值与待注入目标一一对应
所以注入标签顺序随意,调换 < constructor-arg />标签的前后顺序,仍可正确注入数据
留言与评论(共有 0 条评论) “” |