簡體   English   中英

Spring:如何從單個模板定義動態創建多個bean

[英]Spring: how to dynamically create multiple beans from single template definition

我有以下用於在xml中定義的遠程Web服務的Spring bean:

    <bean id="authWSTemplate" class="org.springframework.remoting.jaxws.JaxWsPortProxyFactoryBean" abstract="true">
       <property name="serviceInterface" value="com.example.webservices.Authentication" />
       <property name="wsdlDocumentUrl" value="${ws.root}/authentication?wsdl" />
       <property name="namespaceUri" value="http://security.webservices.example.com/" />
       <property name="serviceName" value="AuthenticationWebService" />
       <property name="portName" value="AuthenticationPort" />
       <property name="maintainSession" value="true" />
    </bean>

如何獲得該bean模板並創建一個具體的bean(即提供root屬性)? 然后可以將混凝土豆放入Spring容器中嗎?

我需要大量指向不同系統的具體bean,因此我具有不同的根值。 對於此示例,假設有兩個具有根目錄的系統: http : //domain1.com : 8001/wshttp://domain2.com:8002/ws

因此,我想要2個名為“ authWSdom1”和“ authWSdom2”的bean。

我希望在應用程序初始化塊中以編程方式進行此操作,在該程序塊中,我將檢索所有已知系統實現的列表(此信息僅在運行時才知道),並為每個impl創建一個bean,緩存bean名稱,然后我的應用程序將在需要時從Spring容器中檢索適當的bean。

還是為此有更好的模式? 也許通過在bean的構造函數中提供根值?

我想我在Spring中不能有一個bean,因為我需要支持跨多個端點的並發訪問(即,多個用戶同時訪問domain1和domain2)。

創建實現BeanFactoryPostProcessor和InitializingBean的自定義bean。 使用postProcessBeanFactory方法創建bean:

public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
    String wsdlDocumentUrl = ....;
    // .......
    registry.registerBeanDefinition(YOUR_BEAN_NAME, BeanDefinitionBuilder.childBeanDefinition(
                getParentNoDomainServicBeanName(authWSTemplate)).addPropertyReference(
                "wsdlDocumentUrl", wsdlDocumentUrl).getBeanDefinition());

}

雖然我相信Ragnor的答案很適合在彈簧容器中動態創建bean的情況,但我還是決定使用spring來定義自己的WSTemplate DTO,然后使用工廠類來使用此DTO並以編程方式進行構建(運行時提供的根URL)並添加DTO后綴值)並緩存生成的JaxWS ProxyBean:

<bean id="authWSTemplate" class="com.example.WSProxyTemplate">
   <property name="serviceInterface" value="com.example.webservices.Authentication" />
   <property name="wsdlDocumentUrlSuffix" value="/authentication?wsdl" />
   <property name="namespaceUri" value="http://security.webservices.example.com/" />
   <property name="serviceName" value="AuthenticationWebService" />
   <property name="portName" value="AuthenticationPort" />
   <property name="maintainSession" value="true" />
</bean>

我喜歡這種方法,因為我的spring配置是從實際使用的WS bean中抽象出來的。 即,如果我想使用JaxWS之外的其他東西,那么我只是寫了一個使用相同DTO bean的不同工廠。 同樣,如果我必須根據某些系統/環境標准在運行時選擇WS實現,這將有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM