首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

Spring 中Bean的自动安装六种模式其四

2012-09-10 
Spring 中Bean的自动装配六种模式其四??Spring?中Bean的自动装配六种模式其四Spring?IoC容器可以自动装配(

Spring 中Bean的自动装配六种模式其四

??Spring?中Bean的自动装配六种模式其四

Spring?IoC容器可以自动装配(autowire)相互协作bean之间的关联关系。因此,如果可能的话,可以自动让Spring通过检查BeanFactory中的内容,来替我们指定bean的协作者(其他被依赖的bean)。autowire一共有六种类型。由于autowire可以针对单个bean进行设置,因此可以让有些bean使用autowire,有些bean不采用。autowire的方便之处在减少或者消除属性或构造器参数的设置,这样可以给我们的配置文件减减肥![2]?在xml配置文件中,可以在<bean/>元素中使用autowire属性指定:

模式

说明

?Constructor

与byType的方式类似,不同之处在于它应用于构造器参数。如果在容器中没有找到与构造器参数类型一致的bean,那么将会抛出异常。?

下来我们就用案例来证明一下:准备3个类:

?

?

public class AddressServiceImpl { /**住址*/private String address; public void setAddress(String address){this.address=address;}}public class HomeAddressServiceImpl extends AddressServiceImpl {private String address;public void setAddress(String address){this.address=address;}public HomeAddressServiceImpl() {super();}public HomeAddressServiceImpl(String address){this.address=address;}}public class EmpServiceImpl {/**公司地址*/private AddressServiceImpl companyAddress;public void setCompanyAddress(AddressServiceImpl companyAddress){this.companyAddress=companyAddress;}}

?

Constructor值的constructor.xml配置文件

??Constructor:与byType的方式类似,不同之处在于它应用于构造器参数。如果在容器中没有找到与构造器参数类型一致的bean,那么将会抛出异常。?

?

?

 <?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-2.0.xsd"> <!-- 配置bean  相同类型只能在 配置文件中出现一次<bean id="homeAddressServiceImpl" scope="prototype">  <property name="address">    <value>北京</value>  </property></bean><!-- 自动装配 采用constructor 构造器中的参数是按照byType进行装配的<bean id="empServiceImpl" scope="singleton" autowire="constructor"/></beans>

?

?测试类:(junit测试)??

  public class App { @Testpublic void test(){ApplicationContext ac=new ClassPathXmlApplicationContext("classpath:byName.xml"); EmpServiceImpl emp = (EmpServiceImpl) ac.getBean("empServiceImpl");}}

?

<!--EndFragment--> 1 楼 _木凡 2011-04-28   这就是构造器类 的,自动装载 2 楼 javawangli 2011-04-28   总共是6种模式 你可以参考http://javawangli.iteye.com/admin/blogs/1010764

热点排行