Spring_DI注入依赖
依赖注入:set注入
依赖:bean对象的创建依赖于容器。
注入:bean对象中的所有属性,由容器来注入。
实体类:
点击查看代码
package com.cn.demo;
import java.util.*;
public class Student {
private String name;//value
private Address address;//ref
private String[] books;
private List hobbys;
private Map card;
private Set games;
private Properties info;
private String wife;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String[] getBooks() {
return books;
}
public void setBooks(String[] books) {
this.books = books;
}
public List getHobbys() {
return hobbys;
}
public void setHobbys(List hobbys) {
this.hobbys = hobbys;
}
public Map getCard() {
return card;
}
public void setCard(Map card) {
this.card = card;
}
public Set getGames() {
return games;
}
public void setGames(Set games) {
this.games = games;
}
public Properties getInfo() {
return info;
}
public void setInfo(Properties info) {
this.info = info;
}
public String getWife() {
return wife;
}
public void setWife(String wife) {
this.wife = wife;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", address=" + address +
", books=" + Arrays.toString(books) +
", hobbys=" + hobbys +
", card=" + card +
", games=" + games +
", info=" + info +
", wife='" + wife + '\'' +
'}';
}
}
点击查看代码
package com.cn.demo;
public class Address {
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Address{" +
"address='" + address + '\'' +
'}';
}
}
xml文件
点击查看代码
<?xml version="1.0" encoding="UTF-8"?>
平凡的世界
追着风筝的人
活着
打篮球
玩游戏
看电影
英雄联盟
王者荣耀
020321752326
杨晨
测试:
点击查看代码
import com.cn.demo.Student;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class StudentTest{
public static void main(String[] args) {
/*获取Spring的上下文对象*/
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
/*我们的对象交给Spring去管理了,我们要使用,直接去取出来即可*/
Student student = (Student) context.getBean("student2");
System.out.println(student.toString());
}
}
结果截图: