JAVA全系列 教程
3762个小节阅读:7088.9k
目录
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
Setter注入一般都是结合无参构造方法一起使用。所以类中有无参构造方法。
xxxxxxxxxx
package com.bjsxt.pojo;
public class People {
private int id;
private String name;
public People() {
}
public People(int id, String name) {
this.id = id;
this.name = name;
}
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;
}
@Override
public String toString() {
return "People{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
重新配置了一个bean标签,并设置id=“peo5”。
通过<property>
标签调用类的setter方法。
xxxxxxxxxx
<bean id="peo5" class="com.bjsxt.pojo.People">
<property name="id" value="2"></property>
<property name="name" value="李四"></property>
</bean>
在测试类中获取peo5的bean,并输出到控制台,查看是否包含设置的值。
也可以让构造注入和设值注入混合使用。这两种方式只要保证有对应的构造方法和setter方法,就可以使用其中一种方式设置部分属性的值。
先保证People中有一个参数的构造方法,并且包含name属性的setter方法。
xxxxxxxxxx
package com.bjsxt.pojo;
public class People {
private int id;
private String name;
public People() {
}
// 只有id属性的构造方法
public People(int id) {
this.id = id;
}
public People(int id, String name) {
this.id = id;
this.name = name;
}
// getter/setter 没有粘贴到文档中
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;
}
@Override
public String toString() {
return "People{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
在配置文件中混合使用两种方式
xxxxxxxxxx
<bean id="peo6" class="com.bjsxt.pojo.People">
<constructor-arg index="0" value="3"></constructor-arg>
<property name="name" value="王五"></property>
</bean>
在测试类中获取peo5的bean,并输出到控制台,查看是否包含设置的值。