2011-07-07 48 views
1

假設ProjectA中有ProjectA(前端)和ProjectB(後端)兩個項目,ProjectA中有兩個ClassA ClassA和ClassB。 現在我需要在ClassA中獲得ClassB的實例。 問題是如何使用Spring和RMI將ClassB注入到ClassA中?什麼要添加到spring.xml中? 我是新來的java,所以如果你可以提供與例子的答案請示例。 在此先感謝!使用RMI進行彈簧依賴注入

public void initializeManager() { 
    InitialContext context = null; 
    if (manager == null) { 
    try { 
     Properties props = TaxFormsConfiguration.getInstance().getProperties(); 
     context = new InitialContext(props); 
     manager = (EFormsManager) context.lookup("taxsystem/EFormsManagerFacade/remote"); 
     if (manager == null) { 
     throw new RuntimeException("EFormsManager is null."); 
     } 
    } catch (Exception e) { 
     logger.error("error in EFormsActionManager.initializeManager: " + e.getMessage()); 
    } 
    } 
} 

回答

2

檢查Spring reference for remoting。優能找到有一個例子(使用RMI章節19.2暴露服務)

相反的情況下查找,您將在XML聲明你的豆子,並通過Spring應用程序上下文獲得它們,例如:

ApplicationContext context = new ClassPathXmlApplicationContext(yourxmlname); 
EFormsManager eFormsManager= (EFormsManager)context.getBean("eFormsManager"); 

XML的RMI服務器端:

<bean id="eFormsManager" class="example.EFormsManagerImpl"> 
    <!-- any additional properties, maybe a DAO? --> 
</bean> 

<bean class="org.springframework.remoting.rmi.RmiServiceExporter"> 
    <!-- does not necessarily have to be the same name as the bean to be exported --> 
    <property name="serviceName" value="EFormsManagerService"/> 
    <property name="service" ref="eFormsManager"/> 
    <property name="serviceInterface" value="example.EFormsManager"/> 
    <!-- defaults to 1099 --> 
    <property name="registryPort" value="1199"/> 
</bean> 

XML在RMI客戶端:

<bean id="eFormsManager" class="org.springframework.remoting.rmi.RmiProxyFactoryBean"> 
    <property name="serviceUrl" value="rmi://HOST:1199/EFormsManagerService"/> 
    <property name="serviceInterface" value="example.EFormsManager"/> 
</bean> 
+0

您好,感謝您的快速RESP ONSE!我之前看到過這個教程,但仍然無法將其應用於我的項目。 具體而言,我有方法「initializeManager()」做我想要但不是通過注射,這裏是代碼 –

+0

public void initializeManager(){ \t InitialContext context = null; \t \t如果(經理== NULL){ \t \t \t嘗試{ \t \t \t \t屬性道具= TaxFormsConfiguration.getInstance()的GetProperties()。 \t \t \t \t context = new InitialContext(props); (EFormsManager)context.lookup(「taxsystem/EFormsManagerFacade/remote」); \t \t \t \t如果(經理== NULL){ \t \t \t \t \t拋出新的RuntimeException( 「EFormsManager爲空」); \t \t \t \t} \t \t \t}趕上(例外五){ \t \t \t \t logger.error( 「在EFormsActionManager.initializeManager錯誤:」 + e.getMessage()); \t \t \t} \t \t} \t} –

+0

現在如果u能請您給一些建議如何做到這一點,我需要刪除此方法,並按照我的理解 - 添加「東西」到spring.xml,但添加什麼我不知道 :( –