1、set⽅法注⼊
配置:
public class Demo {
@Test
public void test(){ //1、创建容器对象
ApplicationContext ac =new ClassPathXmlApplicationContext(\"cn/itcast/injection/applicationContext.xml\"); //2、像容器要User对象
User user = (User)ac.getBean(\"user\"); //3、打印user对象
System.out.println(user.toString()); } }
结果:
2、构造⽅法注⼊
配置:
实体:
package cn.itcast.bean;
public class User { private String name; private Integer age;
private Car car;
public User(String name, Car car) {
System.out.println(\"User(String name, Car car)\"); this.name = name; this.car = car; }
public User(Integer name, Car car) {
System.out.println(\"User(Integer name, Car car)\"); this.name = name+\"\"; this.car = car; }
public User(){
System.out.println(\"user对象空参构造\"); }
public String getName() { return name; }
public void setName(String name) {
this.name = name; }
public Integer getAge() { return age; }
public void setAge(Integer age) { this.age = age; }
public Car getCar() { return car; }
public void setCar(Car car) { this.car = car; }
@Override
public String toString() {
return \"User [name=\" + name + \ } }
demopublic class Demo {
@Test
public void test(){ //1、创建容器对象
ApplicationContext ac =new ClassPathXmlApplicationContext(\"cn/itcast/injection/applicationContext.xml\"); //2、像容器要User对象
User user = (User)ac.getBean(\"user1\"); //3、打印user对象
System.out.println(user.toString()); } }
结果
由 name+index + type 可以任意指定⼀个构造参数
3、p名称空间注⼊
配置
demopublic class Demo {
@Test
public void test(){ //1、创建容器对象
ApplicationContext ac =new ClassPathXmlApplicationContext(\"cn/itcast/injection/applicationContext.xml\"); //2、像容器要User对象
User user = (User)ac.getBean(\"user3\"); //3、打印user对象
System.out.println(user.toString()); }
}
结果:
4、spel注⼊
配置:
demo
public class Demo {
@Test
public void test(){ //1、创建容器对象
ApplicationContext ac =new ClassPathXmlApplicationContext(\"cn/itcast/injection/applicationContext.xml\"); //2、像容器要User对象
User user = (User)ac.getBean(\"user4\"); //3、打印user对象
System.out.println(user.toString()); } }
结果
因篇幅问题不能全部显示,请点此查看更多更全内容