代码地址:spring2.1.zip - 蓝奏云文件大小:15.1 K|https://www.lanzouw.com/imlEwvptwre
Set方法注入的原理是spring先通过指定id的类的无参构造函数创建对象,然后通过set方法进行赋值。所以,使用Set方法注入时必须保证类中定义了无参构造函数和Set方法。
1、定义Category和Product类,给属性设置SetXYZ()方法,spring会通过set方法来给对象赋值
package com.how2j.pojo;
public class Category {
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "Category{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private int id;
private String name;
}
package com.how2j.pojo;
public class Product {
//普通属于类型
private int id;
private String name;
//引用类型
private Category category;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
@Override
public String toString() {
return "Product{" +
"id=" + id +
", name='" + name + '\'' +
", category=" + category +
'}';
}
}
2、编写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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 先定义Category类的jave bean,然后才能在Product中注入Category对象-->
<!-- 使用propertiy注入属性时,对应的类必须有setXYZ方法, 这里的name的值必须是对象类里的setXYZ的xYZ,注意X必须是小写-->
<bean id="c" class="com.how2j.pojo.Category">
<!-- 如果是普通属性,就使用value进行赋值-->
<property name="id" value="1"/>
<property name="name" value="category 1"/>
</bean>
<bean id="p" class="com.how2j.pojo.Product">
<property name="name" value="product1"/>
<!-- 如果是引用类型的属性,就使用ref来注入引用对象, 这里c是定义的的其他的bean的标识,spring会自动创建一个c类型的对象,然后使用setXYZ方法传入到p中-->
<property name="category" ref="c"/>
</bean>
</beans>
3、测试
package test;
import com.how2j.pojo.Category;
import com.how2j.pojo.Product;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestSpring {
@Test
//spring的控制翻转
public void test1(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml" );
Category c = (Category) context.getBean("c");
System.out.println(c);
}
@Test
//测试spring的属性注入
public void test2(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml" );
Product p = (Product) context.getBean("p");
System.out.println(p);
}
}
补充:目录结构如下: