如何覆盖Spring bean定义但仍引用覆盖的bean? [英] How do I override a Spring bean definition yet still reference the overridden bean?

查看:639
本文介绍了如何覆盖Spring bean定义但仍引用覆盖的bean?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过用我的委托服务重写原始服务的bean定义来实现委托服务提供程序.但是,顾名思义,委托服务需要引用原始服务以委托调用.

I'm attempting to implement a delegate Service provider by overriding the bean definition for the original service with my delegate Service. However, as the name would imply, the delegate Service needs a reference to the original service to delegate calls to.

我无法弄清楚如何在使用原始bean def时覆盖bean定义,而又不会遇到循环引用问题.

I'm having trouble figuring out how to override the bean definition while using the original bean def without running into a circular reference issue.

例如:

<!-- Original service def in spring-context.xml -->
<bean id="service" class="com.mycompany.Service"/>

<!-- Overridden definition in spring-plugin-context.xml -->
<bean id="service" class="com.mycompany.DelegatedService"/>
    <constructor-arg ref="service"/>
</bean>

这可能吗?

推荐答案

这个问题的简短答案是,不能有两个同名的bean定义.如果尝试,则其中一个将隐藏另一个,并且只有一个定义可用.

The short answer to your question is that you cannot have two bean definitions with the same name. If you try, one will hide the other, and only one definition will be usable.

您的问题的示例似乎表明您正在尝试将原始的service bean封装在一个代理对象中,并且该包装器在对该服务的调用前后进行一些前后工作.在不定义两个service bean且不修改原始service bean的情况下,实现此目标的一种方法是使用Spring AutoProxyCreator,可能是

Your question's example seems to suggest that you're trying to wrap the original service bean in a proxy object, with the wrapper performing some before-and-after work around calls to the service. One way to achieve this, without defining two service beans, and without modifying the original service bean, is to use a Spring AutoProxyCreator, probably a BeanNameAutoProxyCreator.

这允许您列出要自动代理的一个或多个bean.您可以指定要应用于目标Bean调用的拦截器.您将实现这些拦截器来完成您需要做的工作.

This allows you to list a bean (or beans) that are to be automatically proxied. You specify the interceptors you want to be applied to invocations on the target bean. You would implement these interceptors to do the work you need to do.

Spring会自动为您创建一个委托代理,该代理具有与以前一样的bean id service,但是具有您的附加功能.

Spring would automatically create a delegating proxy for you, which would have the bean id service as before, but with your additional functionality.

这篇关于如何覆盖Spring bean定义但仍引用覆盖的bean?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆