public class Test {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("Beans.xml");
Student student = (Student) ac.getBean("student");
student.show();
}
}
1.常量注入
Beans.xml
2.类注入
Address.java
public class Address {
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
Beans.xml
3.数组注入
Beans.xml
傲慢与偏见基督山伯爵钢铁是怎样炼成的
4.List注入
Beans.xml
看书学习上网写作
5.Set注入
Beans.xml
使命召唤少女卷轴我的世界
6.Map注入
Beans.xml
7.Null注入
Beans.xml
8.Properties注入
Beans.xml
2017000001男名字
9.结果
Student's name = 名字,address = 上海
books = 傲慢与偏见 基督山伯爵 钢铁是怎样炼成的
hobbies = [看书, 学习, 上网, 写作]
games = [使命召唤, 少女卷轴, 我的世界]
bank cards = {招商银行=6462131654486413213, 工商银行=132164612231684684}
wife = null
info = {学号=2017000001, name=名字, sex=男}
10.P命名空间注入
xmlns:p="http://www.springframework.org/schema/p"
User.java 需要Set方法
public class User {
private String name;
private int age;
public void show() {
System.out.println("name = " + name + ", age = " + age);
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
}
Test.java
public class Test {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("Beans.xml");
User user = (User) ac.getBean("user");
user.show();
}
}
Beans.xml
结果
name = 名字, age = 20
11.C命名空间注入
xmlns:c="http://www.springframework.org/schema/c"
User.java 需要带参构造方法
public class User {
private String name;
private int age;
public User(){
super();
}
public User(String name, int age) {
this();
this.name = name;
this.age = age;
}
public void show() {
System.out.println("name = " + name + ", age = " + age);
}
}
Test.java
public class Test {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("Beans.xml");
User user = (User) ac.getBean("user");
user.show();
}
}