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>