有没有可能从 Spring 注入调用 ref bean 方法的结果?

有没有可能从 Spring 注入调用 ref bean 方法的结果?

我试图将两个独立项目的一些剪切/粘贴代码重构为一个公共类。在其中一个项目中,代码位于一个从 Spring 实例化的类中,我称之为“ MyClient”。它被注入另一个 Spring 实例化的类“ MyRegistry”,然后 MyClient 类使用该类查找端点。我真正需要的是重构类中的端点 String,它可以通过 Setter 进行初始化。在重构的代码中,我确实不能从 MyClient 依赖 MyRegistry。

所以,我的问题是... 有没有一种方法可以注入在 MyRegistry 类中查找的 Spring 端点 String。所以,我现在有:

<bean id="registryService" class="foo.MyRegistry">
...properties set etc...
</bean>


<bean id="MyClient" class="foo.MyClient">
<property name="registry" ref="registryService"/>
</bean>

但是我想要(我知道这是假想的 Spring 语法)

<bean id="MyClient" class="foo.MyClient">
<property name="endPoint" value="registryService.getEndPoint('bar')"/>
</bean>

其中 MyRegistry 将有一个方法 getEndPoint (Stirng endPointName)

希望从我努力实现的目标的角度来看,这是有意义的。请让我知道这样的事情是否可能在春天!

72454 次浏览

It's possible in Spring 3.0 via Spring Expression Language:

<bean id="registryService" class="foo.MyRegistry">
...properties set etc...
</bean>


<bean id="MyClient" class="foo.MyClient">
<property name="endPoint" value="#{registryService.getEndPoint('bar')}"/>
</bean>

Or in Spring 2.x, by using a BeanPostProcessor

Typically, bean post processors are used for checking the validity of bean properties or altering bean properties (what you want to) according to particular criteria.

public class MyClientBeanPostProcessor implements BeanPostProcessor, ApplicationContextAware {


private ApplicationContext applicationContext;
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}


public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}


public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if((bean instanceof MyClient)) && (beanName.equals("MyClient"))) {
Myregistry registryService = (Myregistry) applicationContext.getBean("registryService");


((MyClient) bean).setEndPoint(registryService.getEndPoint("bar"));
}


return bean;
}
}

And register your BeanPostProcessor

<bean class="br.com.somthing.MyClientBeanPostProcessor"/>

The nicest solution is to use Spring 3's expression language as described by @ChssPly76, but if you're using an older version of Spring, it's almost as easy:

<bean id="MyClient" class="foo.MyClient">
<property name="endPoint">
<bean factory-bean="registryService" factory-method="getEndPoint">
<constructor-arg value="bar"/>
</bean>
</property>
</bean>