【Spring实战】注入非Spring Bean对象

你们常常用到Spring IOC去管理对象之间的依赖关系,但通常状况下都有一个前提:这些Bean对象必须是经过Spring容器建立实例化的。spring

但实际上,项目中有可能会遇到这样的场景:this

一个类不是经过Spring容器实例化的,而是直接new Object()这种方式建立,这个对象又和别的Spring容器中管理的对象存在依赖关系。code

这时该怎么办呢,固然,咱们能够手动的去调用setXxxx()方法去设置对象之间的依赖,但这样耦合性又过高。还好Spring也提供了注入非Spring Bean对象的功能。orm

如下是《SPring in Action》中的Demo:xml

package com.springinaction.springidol;  
  
import org.springframework.beans.factory.annotation.Configurable;  
  
@Configurable("pianist")  
public class Instrumentalist implements Performer {  
  public Instrumentalist() {}  
    
  public void perform() throws PerformanceException {  
    System.out.print("Playing " + song + " : ");  
    instrument.play();  
  }  
    
  private String song;  
  public void setSong(String song) {  
    this.song = song;  
  }  
    
  private Instrument instrument;  
  public void setInstrument(Instrument instrument) {  
    this.instrument = instrument;  
  }  
}

其中,@Configurable("pianist")做用有两个:对象

1.它表示当前类对象是在Spring容器外实例化的,但仍能够由Spring容器进行配置管理;io

2.它把Instrumentalist类与id为"pianist"的Bean关联起来了,之后当Spring企图配置Instrumentalist实例时,会以pianist Bean为模板。form

<?xml version="1.0" encoding="UTF-8"?>  
  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:aop="http://www.springframework.org/schema/aop"  
    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  
    http://www.springframework.org/schema/aop   
    http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">  
  
  <aop:spring-configured/>  
  
  <bean id="pianist"   
      class="com.springinaction.springidol.Instrumentalist"  
      abstract="true">  
    <property name="song" value="Chopsticks" />  
    <property name="instrument">  
      <bean class="com.springinaction.springidol.Piano" />  
    </property>  
  </bean>  
</beans>

其中,<aop:spring-configured/>的做用是:告诉Spring有一些Bean须要进行配置,包括在Spring容器外建立的Bean对象。模板

相关文章
相关标签/搜索