`
Longmanfei
  • 浏览: 46576 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Spring 自动装配之不能偷懒

阅读更多

Spring之自动装配,所谓自动装配,从字面解读,我想应该不难理解吧(当然不是诱导读者去咬文嚼字)。那究竟spring 自动装配有几种装配类型(我想大家最关注的应该是我们什么时候可以“偷懒”反之什么时候又不能,我想开发者目的应该也是为了简化程序员的工作)。那下面我们就介绍spring自动装配之不能偷懒——autowire="no",在接受之前我们先介绍自动装配总共包括几种装配方式(在其他装配方式中就不在介绍了)

在介绍之前,先简单的提一个问题(自动装配总共有几种呢),答案(六种)也许与大家想的有点背离,但是我个人认为并不是不无道理的。

1. default-autowire="那五种形式"这种是在全局(即在跟标签里)定义的,如果局部定义了autowire 可想而知,当然是按照局部的去进行自动装配了,如果没有定义就是按照跟标签的默认定义去进行装配,所以在这里把它单独拿出来作为一种

2. No:通过ref元素指定依赖

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

4. byType:在容器中寻找一个与需要自动装配的属性类型相同的Bean;如果没有找到相符的Bean,该属性就没有被装配上,如果找到超过一个相符的Bean抛出异常org.springframework.beans.factory.UnsatisfiedDependencyException(特此声明测试针对spring2.5.6,spring3.0中检查到多个Bean貌似没有异常并且在3.0中没有依赖检查这个属性)

5. Constructor:在容器中查找与需要自动装配的Bean的构造方法参数一致的一个或者过个Bean,如果从在不确定的Bean或构造方法,容器会抛出异常org.springframework.beans.factory.UnsatisfiedDependencyException.

6. Autodetect:首先我们尝试使用constructor来自动装配,然后使用byType方式。不确定行的处理与constuctorbyType方式一样

既然我们的题目叫不能偷懒,那当然我们就要介绍no

//Longmanfei.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.5.xsd">

<bean id="greetingDaoImpl" class="cn.csdn.dao.GreetingDaoImpl" >

<!-- 通过set方法进行注入 -->

<property name="say" value="你好"></property>  

    </bean>

<bean id="greetingServiceImpl"

class="cn.csdn.service.GreetingServiceImpl" autowire="no">

<property name="gdi" ref="greetingDaoImpl"></property>

</bean>

   </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;

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:Longmanfei.xml");

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

   GreetingService

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

   gs.say();

   

   }

 

 

2
6
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics