src\dayday\Person.java
package dayday; /** * Created by I am master on 2016/11/28. */ public class Person { private String name; private int age; private City city; private Car car; public void setName(String name){ this.name=name; } public void setAge(int age){ this.age=age; } public void setCity(City city){ this.city=city; } public void setCar(Car car){ this.car=car; } public void toprint(){ System.out.println("["+"name="+name+" age="+age+" car"+car+" city"+city+"]"); } }
src\daydayCity.java
package dayday; /** * Created by I am master on 2016/11/28. */ public class City { private String livecity; private String street; public void setLivecity(String livecity) { this.livecity=livecity; } public void setStreet(String street{ this.street=street; } public String getLivecity(){ return livecity; } public String getStreet(){ return street; } public String toString(){ return "["+"city="+livecity+" street"+street +"]"; } }
src\dayday\Car.java
package dayday; /** * Created by I am master on 2016/11/28. */ public class Car { private String name; public void setName(String name){ this.name=name; } public String getName(){ return name; } public String toString(){ return "["+"carname="+name+"]"; } }
src\dayday\Main.java
package dayday; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Created by I am master on 2016/11/28. */ public class Main { public static void main(String[] args){ ApplicationContext ctx= new ClassPathXmlApplicationContext("beans.xml"); Person person1=ctx.getBean("person1",Person.class); Person person2=ctx.getBean("person1",Person.class); person1.toprint(); person2.toprint(); } }
src\beans.xml<?xml version="1.0" encoding="UTF-8"?>
运行结果
[name=dayday age=18 car[carname=Audi] city[city=shaoxing streetxinchang]]
[name=dayday age=18 car[carname=Audi] city[city=shaoxing streetxinchang]]
装配机制
byName根据bean的名字和当前bean的setter风格的属性名进行自动匹配,若有匹配的,则进行自动装配,若没有匹配的,则不装配
比如bean中有setXXX()的方法,且在配置文件中,bean中id="XXX"则可进行自动装配,id="XXX1"就不可以装配
byType根据bean的类型和当前bean的属性进行自动装配,若IOC容器中有一个及以上的类型匹配的bean,则将抛出异常
在实际开发中很少用自动装配,因为代码不够一目了然,而且存在很多局限性,如不能两种装配方式同时进行,如果选择了自动了装配,就不能手动配置...