Programing

Spring에서 ref bean에 메서드를 호출 한 결과를 주입 할 수 있습니까?

lottogame 2020. 10. 29. 07:44
반응형

Spring에서 ref bean에 메서드를 호출 한 결과를 주입 할 수 있습니까?


Spring에서 ref bean에 메서드를 호출 한 결과를 주입 할 수 있습니까?

두 개의 개별 프로젝트에서 잘라내거나 붙여 넣은 코드를 공통 클래스로 리팩터링하려고합니다. 프로젝트 중 하나에서 코드는 Spring에서 인스턴스화되는 "MyClient"라고 부르는 클래스에 있습니다. 다른 스프링 인스턴스화 된 클래스 "MyRegistry"가 주입 된 다음 MyClient 클래스는 해당 클래스를 사용하여 엔드 포인트를 찾습니다. 내가 정말로 필요한 것은 Setter를 통해 초기화 할 수있는 리팩토링 된 클래스의 끝점 String입니다. 리팩터링 된 코드에서 MyClient의 MyRegistry에 대한 종속성을 가질 수 없습니다.

그래서, 내 질문은 이것이 ... MyRegistry 클래스에서 조회 된 스프링에서 끝점 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) 메소드가 있습니다.

내가 이루고자하는 것의 관점에서 보면 그것이 의미가있는 희망입니다. 봄에 이런 일이 가능하면 알려주세요!


가장 좋은 해결책은 @ ChssPly76에 설명 된대로 Spring 3의 표현 언어를 사용하는 것이지만, 이전 버전의 Spring을 사용하는 경우 거의 다음과 같이 쉽습니다.

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

Spring Expression Language 를 통해 Spring 3.0에서 가능합니다 .

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

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

또는 Spring 2.x에서 BeanPostProcessor를 사용하여

일반적으로 빈 포스트 프로세서는 빈 속성의 유효성을 확인 하거나 특정 기준에 따라 빈 속성 (원하는 것)을 변경 하는 데 사용됩니다 .

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;
    }
}

그리고 귀하의 BeanPostProcessor를 등록하십시오

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

참고 URL : https://stackoverflow.com/questions/2520722/is-it-possible-from-spring-to-inject-the-result-of-calling-a-method-on-a-ref-bea

반응형