bean:
package s.t;
public class Car {
private Integer id;
private String color;
public Car() {
super();
}
public Car(Integer id, String color) {
super();
this.id = id;
this.color = color;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
@Override
public String toString() {
return "Car [id=" + id + ", color=" + color + "]";
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd ">
<bean id="car" class="s.t.Car"> <!-- 属性注入 -->
<property name="id">
<value>2</value>
</property>
<property name="color">
<value>red</value>
</property>
</bean>
<bean id="cc" class="s.t.Car"> <!-- 构造器注入 -->
<constructor-arg index="0" type="java.lang.Integer">
<value>3</value>
</constructor-arg>
<constructor-arg index="1" type="java.lang.String">
<value>orange</value>
</constructor-arg>
</bean>
<bean id="cb" class="s.t.CarFactory" factory-method="getCar"></bean> <!--工厂方法注入 -->
</beans>
测试:
package s.t;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class T1 {
public static void main(String[] args) {
ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("spring/spring.xml");
Car car = (Car) app.getBean("cc");
System.out.println(car);
}
}
id="car"是属性注入,此时需要有无参构造器和setter方法,id="cc" 是构造器注入,通过index和type确定调用的构造器。