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

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

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

模式

说明

  ByNname

根据属性名自动装配。此选项将检查容器并根据名字查找与属性完全一致的bean,并将其与属性自动装配。例如,在bean定义中将autowire设置为by name,而该bean包含master属性(同时提供setMaster(..)方法),Spring就会查找名为masterbean定义,并用它来装配给master属性。

下来我们就用案例来证明一下:准备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;

}

}

 

byName值的byname.xml配置文件

 

 

 

 <?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 id="homeAddressServiceImpl" class="cn.csdn.service.HomeAddressServiceImpl"

scope="singleton">

<property name="address">

<value>北京海淀上地软件园</value>

</property> 

</bean>

<bean id="empServiceImpl" class="cn.csdn.service.EmpServiceImpl"

scope="singleton" autowire="byName" />

</beans>

 

 测试类:(junit测试)  

 

 

 public class App { 

@Test

public void test(){

ApplicationContext ac=new ClassPathXmlApplicationContext("classpath:byName.xml"); EmpServiceImpl emp = (EmpServiceImpl) ac.getBean("empServiceImpl");

}

}

 

 注意:

   byName

   在使用的过程中必须保证bean能够初始化,否则的话会出现bug

   如果有默认的无参数的构造器就不需要多余的配置

   如果有带有参数的构造器,那在bean的配置中必须配置器初始化的参数 或者在bean中添加无参数的构造器

<!--EndFragment-->
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值