属性setter方法注入是Spring最主流的注入方法,这种注入方法简单、直观,它是在被注入的类中声明一个setter方法,通过setter方法的参数注入对应的值。
案例:
① 创建User2实体,配置setter方法
package com.lq.entities;
/**
* @Author: Luqing Teacher
* @CreateTime: 2024-11-27
* @Description: 用户2
* @Version: 1.0
*/
public class User2 {
private int id;
private String name;
private String pwd;
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 String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
@Override
public String toString() {
return "User2{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
}
② 创建applicationContext-user2.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">
<bean id="user2" class="com.lq.entities.User2">
<property name="id" value="2"></property>
<property name="name" value="lq2"></property>
<property name="pwd" value="456"></property>
</bean>
</beans>
③ 测试类
package com.lq.test;
import com.lq.entities.User2;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @Author: Luqing Teacher
* @CreateTime: 2024-11-27
* @Description: 测试2
* @Version: 1.0
*/
public class TestUser2 {
public static void main(String[] args)
{
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext-user2.xml");
User2 user2 = applicationContext.getBean("user2", User2.class);
System.out.println(user2);
}
}
④ 结果如下: