目的:使用spring得到一个已经注入属性的对象
-
导入依赖
org.springframework spring-context 5.3.9 junit junit 4.13.1 test -
写实体类
package com.xxx.pojo; public class Dog { String name; int age; public Dog(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return "Dog{" + "name='" + name + ''' + ", age=" + age + '}'; } } -
写xml文件
constructor-arg标签可以使用三种方式
name/type/index
也就是名字,参数类型,索引
当然如果参数类型一样则玩不转了
-
写测试类
import com.xxx.pojo.Dog; import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MyTest { @Test public void test01() { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean.xml"); Dog dog = context.getBean("dog", Dog.class); System.out.println(dog); } }



