spring自动装配

package com.test.autowire;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

/**
 * byName:通过属性名进行查找,该模式下,spring会查找一个与待装配Bean属性同名的Bean。
 * byType:通过类型进行自动装配。该模式下,spring会查找一个与待装配Bean属性同类型的Bean。
 *     不过,如果找到有一个以上这样的Bean,则会抛出致命异常
 *
 * 依赖检查用于确保所有的或者部分Bean属性,是否得到了正确设置。dependency-check属性值有以下几种:
 * none:不进行依赖检查
 * simple:对基本类型和集合进行依赖检查
 * object:对协作者进行依赖检查
 * all:对协作者,基本类型和集合都进行依赖检查
 *
 * @author user
 *
 */
public class AutoWireUsage {

 public static void main(String[] args) {
  Resource resource = new ClassPathResource("com/test/autowire/autowire-byType.xml");
  BeanFactory factory = new XmlBeanFactory(resource);
  System.out.println(factory.getBean("setterBean"));
  
  resource = new ClassPathResource("com/test/autowire/autowire-byName.xml");
  factory = new XmlBeanFactory(resource);
  System.out.println(factory.getBean("setterBean"));
 }
}

autowire-byName.xml内容

<bean id="setterBean" class="com.test.injection.SetterBeanUsage" autowire="byName" dependency-check="objects"></bean>
 <bean id="beanOne" class="com.test.injection.AnotherBean"></bean>
 <bean id="beanTwo" class="com.test.injection.YetAnotherBean"></bean>

 

autowire-byType.xml内容

<bean id="setterBean" class="com.test.injection.SetterBeanUsage" autowire="byType"></bean>
 <bean id="anotherBean" class="com.test.injection.AnotherBean"></bean>
 <bean id="yetAnotherBean" class="com.test.injection.YetAnotherBean"></bean>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值