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

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

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

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

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

以下是《SPring in Action》中的Demo:

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容器进行配置管理;

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

<?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对象。


转载于:https://my.oschina.net/u/1866821/blog/364381

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值