spring02:DI(依赖注入)
文章目录
- spring02:DI(依赖注入)
- 前言:
- 一、构造器注入
- 二、set注入:
- 1. Student类:
- 2. Address类:
- 3. beans.xml:
- 4. MyTest:
- 三、拓展方式注入:p命名空间 和 c命名空间(property和constructor)
- 1. User类:
- 2. UserBean.xml:
- 总结
前言:
提示:以下是本篇文章正文内容:
一、构造器注入
二、set注入:
1. Student类:
2. Address类:
public class Address {
private String address;
public Address() {
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Address{" +
"address='" + address + '\'' +
'}';
}
}
3. beans.xml:
4. MyTest:
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Student stu = (Student) context.getBean("student");
System.out.println(stu.toString());
/*
Student{
name='胡潇',
address=Address{address='内蒙古工业大学'},
books=[西游记, 三国演义, 水浒传, 红楼梦],
hobbys=[听歌, 敲代码, 敲代码],
cards={
身份证=1234568876789876543,
银行卡=1234567876543212345623
},
games=[LOL, BOB, QAQ],
info={
学号=20191800074,
url=男,
username=胡潇
},
wife='null'}
*/
}
}
三、拓展方式注入:p命名空间 和 c命名空间(property和constructor)
1. User类:
public class User {
private String name;
private int age;
public User() {
}
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
2. UserBean.xml:
总结
提示:这里对文章进行总结:
💕💕💕