---
title: "Spring 自动装配之不得不\"懒\"（一）"
author: "Longmanfei"
date: "2011-04-19T22:46:50Z"
tags: ["Bean", "IOC", "Spring", "XML", "junit"]
categories: ["企业架构"]
slug: "spring"
draft: false
lastmod: "2011-04-19T22:46:50Z"
id: 1008538
url: "https://longmanfei.iteye.com/blog/1008538"
---

这次我们来介绍spring的另一种自动装配方式byName，首先我们单独的看它应该跟名字有什么直接或者间接的联系。为了例证我们的推断，我们当然要看其定义了。

1. byName:在容器中寻找和需要自动装配的属性名相同的Bean(或ID),如果没有找到相符的Bean,该属性就没有被装配上。

大概就是我们的理解根据属性的名字到xml中寻找相应的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.5.xsd"

 >

<!--根据id检索-->

<bean id="greetingDaoImpl" 

class="cn.csdn.dao.GreetingDaoImpl" scope="singleton">

<property name="say">

<value>Longmanfei</value>

</property>

</bean>

<bean id="greetingServiceImpl"

class="cn.csdn.service.GreetingServiceImpl"

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

</beans>

//GreetingDaoImpl

public class GreetingDaoImpl implements GreetingDao {

    private String say;

public void say() {

System.out.println("我打了这个招呼"+say);

}

public void setSay(String say) {

this.say = say;

}

    

}

//GreetingServiceImpl

public class GreetingServiceImpl implements GreetingService{

    private GreetingDaoImpl greetingDaoImpl;//注意属性名称和xml里的id

public void say() {

greetingDaoImpl.say();

}

public void setGreetingDaoImpl(GreetingDaoImpl gdi) {

System.out.println("我调用了set方法");

this.greetingDaoImpl = gdi;

}




public GreetingServiceImpl() {

super();

System.out.println("我调用了空的构造器");

}


public GreetingServiceImpl(GreetingDaoImpl greetingDaoImpl) {

super();

System.out.println("我调用了有参的构造器");

this.greetingDaoImpl = greetingDaoImpl;

}




    

}

//junit测试

 @Test

   public void test1(){

   /*加载spring容器可以解析多个配置文件采用数组方式传递*/

   ApplicationContext

   ac=New ClassPathXmlApplicationContext("classpath：LongmanfeibyName.xml");

   //直接转换成接口便于日后修改数据/*Ioc控制反转体现*/

   GreetingService

      gs=(GreetingService) ac.getBean("greetingServiceImpl");

      gs.say();

   

      }
```

 

&lt;!--EndFragment--&gt;