1)使用构造器注入bean
实体类:用户类
public class User {
private String name;
private UserMessage userMessage;
public User() {
}
public User(String name, UserMessage userMessage) {
this.name = name;
this.userMessage = userMessage;
}
@Override
public String toString() {
return "User{" + "name='" + name + '\'' + ", userMessage=" + userMessage + '}';
}
}
实体类:用户信息类
public class UserMessage {
private String username;
private String password;
public UserMessage() {
}
public UserMessage(String username, String password) {
this.username = username;
this.password = password;
}
@Override
public String toString() {
return "UserMessage{" + "username='" + username + '\'' + ", password='" + password + '\'' + '}';
}
}
配置文件
测试类
public class TestDI {
@Test
public void test() {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
User user = ac.getBean("user", User.class);
System.out.println(user);
}
}
测试结果
User{name='tom', userMessage=UserMessage{username='scott', password='tiger'}}
2)使用setter方法注入bean
实体类:用户类
public class User {
private String name;
private UserMessage userMessage;
public User() {
}
public User(String name, UserMessage userMessage) {
this.name = name;
this.userMessage = userMessage;
}
@Override
public String toString() {
return "User{" + "name='" + name + '\'' + ", userMessage=" + userMessage + '}';
}
}
实体类:用户信息类
public class UserMessage {
private String username;
private String password;
public UserMessage() {
}
public UserMessage(String username, String password) {
this.username = username;
this.password = password;
}
@Override
public String toString() {
return "UserMessage{" + "username='" + username + '\'' + ", password='" + password + '\'' + '}';
}
}
配置文件
测试类
public class TestDI {
@Test
public void test() {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
User user = ac.getBean("user", User.class);
System.out.println(user);
}
}
测试结果
User{name='tom', userMessage=UserMessage{username='scott', password='tiger'}}