实体类和工厂类
public class User {
private String name;
private int age;
private Car car;
private List<Car> list;
private Map<String,Car> map;
private Properties prop;
public User(){}
public User(int age, Map<String, Car> map,Car car) {
this.age = age;
this.map = map;
this.car=car;
}
......省略set,get方法
}
public class Car {
private String name;
private double price;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
public class CarFactory {
public static Car getCar(){
return new Car();
}
public Car getNonstaticCar(){
return new Car();
}
}
1、setter
<bean id="user" class="com.miaopu.www.bean.User" lazy-init="true">
<property name="name" value="张三"></property>
<property name="age" value="12"></property>
<property name="car" ref="car1"></property>
<!--实体类内list-->
<property name="list">
<list>
<ref bean="car1"/>
<ref bean="car2"/>
</list>
</property>
<!--实体类内map-->
<property name="map">
<map>
<entry key="123" value-ref="car1"></entry>
<entry key="456" value-ref="car2"></entry>
</map>
</property>
<!--实体类内properties-->
<property name="prop">
<props>
<prop key="1001">小明</prop>
<prop key="1002">小强</prop>
</props>
</property>
</bean>
2、构造器
<bean id="user2" class="com.miaopu.www.bean.User">
<constructor-arg index="0" name="age" type="int" value="#{user.age}" />
<constructor-arg index="1" name="map" type="java.util.Map" >
<map>
<entry key="carname" value-ref="car1"></entry>
</map>
</constructor-arg>
<constructor-arg index="2" name="car" ref="car1" type="com.miaopu.www.bean.Car"/>
</bean>
3、工厂
<!--静态工厂-->
<bean id="car1" class="com.miaopu.www.CarFactory.CarFactory" factory-method="getCar">
<property name="name" value="奔驰"/>
<property name="price" value="1234"/>
</bean>
<!--非静态工厂-->
<bean id="carFactory" class="com.miaopu.www.CarFactory.CarFactory"/>
<bean id="car2" factory-bean="carFactory" factory-method="getNonstaticCar">
<property name="name" value="宝马"/>
<property name="price" value="5678"/>
</bean>
测试类
public class TestIOC {
public static void main(String[] args) {
ClassPathXmlApplicationContext cpac=new ClassPathXmlApplicationContext("classpath:springioctest.xml");
User user=(User)cpac.getBean("user");
//cpac.getBean(User.class);
System.out.println(user);
//另一种getBean方法
/*FileSystemXmlApplicationContext fileXML=new FileSystemXmlApplicationContext("classpath:springtest.xml");
User user=(User)fileXML.getBean("user");
System.out.println(user);*/
}
User [name=张三,
age=12,
car=Car [name=奔驰, price=1234.0],
list=[Car [name=奔驰, price=1234.0], Car [name=宝马, price=5678.0]],
map={123=Car [name=奔驰, price=1234.0], 456=Car [name=宝马, price=5678.0]},
prop={1002=小强, 1001=小明}]