1、值注入
创建我们要使用的User类:
package cn.it.bean;public class User {private String name;@Overridepublic String toString() {return "User [name=" + name + ", age=" + age + "]";}private int age;
// private Car car;
//
// public Car getCar() {
// return car;
// }
//
// public void setCar(Car car) {
// this.car = car;
// }public User() {System.out.println("无参构造方法");}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;}}
在配置文件里配置:
<bean name="user" class="cn.it.bean.User"><property name="name" value="tom"></property><property name="age" value="18"></property></bean>
写一个测试类:
package cn.it.injection;import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;import cn.it.bean.User;public class Demo {@Testpublic void fun() {ApplicationContext ac = new ClassPathXmlApplicationContext("cn/it/injection/applicationContext.xml");User user = (User) ac.getBean("user");System.out.println(user);}
}
运行结果:
2、引用类型注入;
在编写一个新的Car类:
package cn.it.bean;public class Car {private String name;private String color;public String getName() {return name;}public void setName(String name) {this.name = name;}public String getColor() {return color;}public void setColor(String color) {this.color = color;}@Overridepublic String toString() {return "Car [name=" + name + ", color=" + color + "]";}}
将User类改成如下代码:
package cn.it.bean;public class User {private String name;private int age;private Car car;public Car getCar() {return car;}public void setCar(Car car) {this.car = car;}public User() {System.out.println("无参构造方法");}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;}@Overridepublic String toString() {return "User [name=" + name + ", age=" + age + ", car=" + car + "]";}}
在配置文件里配置如下:
<bean name="user" class="cn.it.bean.User"><property name="name" value="tom"></property><property name="age" value="18"></property><property name="car" ref="car"></property></bean><bean name="car" class="cn.it.bean.Car"><property name="name" value="宝马"></property><property name="color" value="红色"></property></bean>
上面的测试类不用改变,直接运行,结果如下: