目录
1.构造方法注入
User1
public class User1 {
private int id;
private String name;
private String passWord;
public User1(int id, String name, String passWord) {
this.id = id;
this.name = name;
this.passWord = passWord;
}
@Override
public String toString() {
return "User1{" +
"id=" + id +
", name='" + name + '\'' +
", passWord='" + passWord + '\'' +
'}';
}
}
applicationContext.xml
applicationContext.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="user1" class="com.chang.pojo.User1">
<constructor-arg name="id" value="1"/>
<constructor-arg name="name" value="张三"/>
<constructor-arg name="passWord" value="123"/>
</bean>
</beans>
TestUser1
public class TestUser1 {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
User1 user1 = context.getBean("user1", User1.class);
System.out.println(user1);
}
}
测试结果
2.属性setter方法注入
User2
public class User2 {
private int id;
private String name;
private String passWord;
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
@Override
public String toString() {
return "User2{" +
"id=" + id +
", name='" + name + '\'' +
", passWord='" + passWord + '\'' +
'}';
}
}
applicationContext.xml
applicationContext.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">
<!-- 第二种方法:setter方法注入-->
<bean id="user2" class="com.chang.pojo.User2">
<property name="id" value="2"/>
<property name="name" value="李四"/>
<property name="passWord" value="456"/>
</bean>
</beans>
TestUser2
public class TestUser2 {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
User2 user2 = context.getBean("user2", User2.class);
System.out.println(user2);
}
}
测试结果