您的位置:首页 > 编程语言 > Java开发

Spring的自动装配机制

2007-03-26 17:04 295 查看
Spring提供一种自动装配,功能,就是不再使用ref进行手工装配bean,这种方式可以减少配置文件的代码量,但是,在大型项目中,不推荐使用,容易混乱,Spring提供byName,byType,constructor,autpdetect四种自动装备方式:

定义接口:




package Bean.autowire;






public interface Dog ...{


public void chop();


}






package Bean.autowire;






public interface Person ...{


public void useDog();


}



定义实现类:


package Bean.autowire;






public class Gundog implements Dog ...{


private String name;




public String getName() ...{


return name;


}




public void setName(String name) ...{


this.name = name;


}




public void chop() ...{


System.out.println(name);




}




}






package Bean.autowire;








import Bean.autowire.Person;






public class Chinese implements Person ...{




public void useDog() ...{


gundog.chop();





}







public Chinese(Dog dog)...{


this.setGundog(dog);


}




private Dog gundog;






public Dog getGundog() ...{


return gundog;


}






public void setGundog(Dog gundog) ...{


this.gundog = gundog;


}


}



配置文件:

byName方式,必须在实现类Chinese中有一个setter方法,必须是set+bean名,首字母大写,如:

public void setGundog(Dog gundog) {
this.gundog = gundog;
}

byType方式,必须有setter方法,要求setter方法的参数类型与容易bean的类型相同,如:

public void setDog(Dog dog) {
this.dog = dog;
}

constructor方式,必须有何bean类型复合,数量复合的构造函数,如:

public Chinese(Dog dog){
this.setGundog(dog);
}






<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">




<beans>










<!-- byname


<bean id="chinese" class="Bean.autowire.Chinese" autowire="byName"></bean>


<bean id="gundog" class="Bean.autowire.Gundog">


<property name="name">


<value>byname</value>


</property>


</bean>


-->


<!-- bytype


<bean id="chinese" class="Bean.autowire.Chinese" autowire="byType"></bean>


<bean id="gundog" class="Bean.autowire.Gundog">


<property name="name">


<value>bytype</value>


</property>


</bean>


-->


<!-- byconstructor


<bean id="chinese" class="Bean.autowire.Chinese" autowire="constructor"></bean>


<bean id="dog" class="Bean.autowire.Gundog">


<property name="name">


<value>byconstructor</value>


</property>


</bean>


-->


</beans>

测试代码:






public static void main(String[] args) throws Exception ...{





String path=new Test().getClass().getResource("/").getPath();


String realpath=path.substring(1, path.length());


ApplicationContext context=new FileSystemXmlApplicationContext(realpath+"/autowire.xml");








Person person1=(Person)context.getBean("chinese");


person1.useDog();








}

运行结果:

可以分别打印注入bean的属性,byname,bytype.constructor

autodetect是自动根据bean的内部结构选择constructor或者byType
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: