多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
案例代码:https://gitee.com/flymini/codes01/tree/master/spring_/com-learn-spring03 *** 在 IoC 容器中注入属性一共有下面 3 种方式。 ``` 1. Setter方法注入,需要提供属性的Setter方法。 2. 构造器注入,需要提供对应的构造器。 3. 命名空间注入,需要提供属性的Setter方法。 ``` **1. 创建一个实体类** ```java @Data public class Student { private String name; private Integer age; private Integer total; private String idCard; public Student(Integer age, Integer total) { this.age = age; this.total = total; } } ``` **2. 在 IoC 容器中注入属性** ```xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:utils="http://www.springframework.org/schema/util" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd"> <!-- p:attrName 是按照命名空间注入 --> <bean id="student" class="com.learn.spring03.pojo.Student" p:idCard="17511222222"> <!-- property是通过Setter注入 --> <property name="name" value="张三"/> <!-- constructor-arg是通过构造器注入 name:按照构造器中参数名注入; index:按照构造器中参数位置注入,从左到右,索引从0开始 --> <constructor-arg name="age" value="25"/> <constructor-arg index="1" value="175"/> </bean> </beans> ``` **3. 测试** ```java public class StudentTest { /** * 获取 IoC 容器 */ private final ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContentext.xml"); @Test public void testStudent() { Student student = context.getBean("student", Student.class); //Student(name=张三, age=25, total=175, idCard=17511222222) System.out.println(student); } } ```