目的:使用spring得到一个已经注入属性的对象
-
导入依赖
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.3.9</version> </dependency> <!-- https://mvnrepository.com/artifact/junit/junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.1</version> <scope>test</scope> </dependency>
-
写实体类
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
也就是名字,参数类型,索引
当然如果参数类型一样则玩不转了
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 一些bean标签--> <bean id="dog" class="com.xxx.pojo.Dog"> <constructor-arg name="age" value="3"/> <constructor-arg name="name" value="二狗子"/> </bean> </beans>
-
写测试类
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); } }