Spring的依赖注入
2021-01-23 21:15
标签:getname app location res 西游 return ext ack 实体 依赖注入:Set注入 ? 依赖: bean对象的创建依赖于容器 ? 注入: bean对象中的所有属性,由容器来注入 实体类 xml文件 测试类 Spring的依赖注入 标签:getname app location res 西游 return ext ack 实体 原文地址:https://www.cnblogs.com/liqiliang1437/p/12881197.htmlspring依赖注入
1.构造器注入
2.Set方式注入
package com.liqiliang.pojo;
import java.util.*;
public class Student {
private String name;
private Address address;
private String[] books;
private List
package com.liqiliang.pojo;
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 + ‘\‘‘ +
‘}‘;
}
}
import com.liqiliang.pojo.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext("bean.xml");
Student student = (Student) applicationContext.getBean("student");
System.out.println(student.toString());
/*
Student{
name=‘李启亮‘,
address=Address{address=‘上海‘},
books=[红楼梦, 西游记, 三国演义],
hobbys=[听课, 敲代码, 看电影],
card={学号=1, 性别=男, 年龄=18},
games=[LOL, CF, QQcar],
wife=‘null‘,
info={学号=20200513, password=4, url=2, driver=1, 姓名=小李, username=3}}
*/
}
}
3.拓展方式注入(p命名空间和c命名空间)
package com.liqiliang.pojo;
public class User {
private int id;
private String name;
public User(int id, String name) {
this.id = id;
this.name = name;
}
public User() {
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name=‘" + name + ‘\‘‘ +
‘}‘;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
import com.liqiliang.pojo.Student;
import com.liqiliang.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
@Test
public void test2(){
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext("UserBean.xml");
User user = (User) applicationContext.getBean("user");
System.out.println(user);
}
@Test
public void test3(){
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext("UserBean.xml");
User user = (User) applicationContext.getBean("user2");
System.out.println(user);
}
}