1、List、Set、Map、Properties集合注入
实体类
public class User {
private List hobit;
private Set subject;
private Map score;
private Properties db;
public User() {
}
public User(List hobit, Set subject, Map score, Properties db) {
this.hobit = hobit;
this.subject = subject;
this.score = score;
this.db = db;
}
public List getHobit() {
return hobit;
}
public void setHobit(List hobit) {
this.hobit = hobit;
}
public Set getSubject() {
return subject;
}
public void setSubject(Set subject) {
this.subject = subject;
}
public Map getScore() {
return score;
}
public void setScore(Map score) {
this.score = score;
}
public Properties getDb() {
return db;
}
public void setDb(Properties db) {
this.db = db;
}
@Override
public String toString() {
return "User{" +
"hobit=" + hobit +
", subject=" + subject +
", score=" + score +
", db=" + db +
'}';
}
}
数据库配置文件(db.properties)
driverClassName = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/eesy
username = root
password = root
配置文件(applicationContext.xml)
电影
音乐
阅读
阅读
Chinese
Math
English
English
测试类
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{hobit=[电影, 音乐, 阅读, 阅读], subject=[Chinese, Math, English], score={Chinese=80.0, Math=86.0, English=90.0}, db={password=root, url=jdbc:mysql://localhost:3306/eesy, driverClassName=com.mysql.jdbc.Driver, username=root}}
2、引用的方式注入集合
实体类
public class User {
private List hobit;
private Set subject;
private Map score;
private Properties db;
public User() {
}
public User(List hobit, Set subject, Map score, Properties db) {
this.hobit = hobit;
this.subject = subject;
this.score = score;
this.db = db;
}
public List getHobit() {
return hobit;
}
public void setHobit(List hobit) {
this.hobit = hobit;
}
public Set getSubject() {
return subject;
}
public void setSubject(Set subject) {
this.subject = subject;
}
public Map getScore() {
return score;
}
public void setScore(Map score) {
this.score = score;
}
public Properties getDb() {
return db;
}
public void setDb(Properties db) {
this.db = db;
}
@Override
public String toString() {
return "User{" +
"hobit=" + hobit +
", subject=" + subject +
", score=" + score +
", db=" + db +
'}';
}
}
数据库配置文件(db.properties)
driverClassName = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/eesy
username = root
password = root
配置文件(applicationContext.xml)
电影
音乐
阅读
阅读
Chinese
Math
English
English
scott
tiger
测试类
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{hobit=[电影, 音乐, 阅读, 阅读], subject=[Chinese, Math, English], score={Chinese=80.0, Math=86.0, English=90.0}, db={password=root, url=jdbc:mysql://localhost:3306/eesy, driverClassName=com.mysql.jdbc.Driver, username=root}}