Is it possible from Spring to inject the result of calling a method on a ref bean?

前端 未结 3 455
清歌不尽
清歌不尽 2020-12-07 14:38

Is it possible from Spring to inject the result of calling a method on a ref bean?

I\'m trying to refactor some cut/pasted code from two separate projects into a co

相关标签:
3条回答
  • 2020-12-07 14:54

    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>
    
    0 讨论(0)
  • 2020-12-07 14:55

    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>
    
    0 讨论(0)
  • 2020-12-07 15:05

    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"/>
    
    0 讨论(0)
提交回复
热议问题