2016-02-19 76 views
0

我想在運行時基於變量實現接口。在運行時實現接口Java EE和Spring

例子:

Class A implements interface1 { 
    public getValue() {} 
} 

Class B implements interface1 { 
    public getValue() {} 
} 

所以我想有可變坐在配置...,例如ClasstoImplement=A

所以,如果ClasstoImplement=A,然後我需要調用類A.getValue()

如果ClasstoImplement=B,那麼我需要在運行時調用類B.getValue()。我應該可以在運行時更改ClasstoImplement的值。

我的應用程序基於Spring,並運行在Tomcat中。

有人可以幫我找出是否有任何方法?

+0

你可以只注入兩種實現到類,並調用基於讀取正確的外部存儲的配置參數。 –

回答

0

有很多可能的解決方案。其中之一是使用org.springframework.aop.target.HotSwappableTargetSource。 看一看實現,可以考慮:

public class CustomSwappable<T> implements Interface1 { 

    private HotSwappableTargetSource targetSource; 

    private String key; 

    private Map<String, T> swappableBeans; 

    @PostConstruct 
    private void init() { 
     targetSource = new HotSwappableTargetSource(swappableBeans.values().iterator().next()); // first is the default 
    } 

    // you need to track changes in config and call this method if any modifications were done 
    public void configChanged(String key, String value) { 
     if (!this.key.equals(key)) { 
      return; 
     } 
     if (!swappableBeans.containsKey(value)) { 
      return; 
     } 
     targetSource.swap(swappableBeans.get(value)); 
    } 

    @Override 
    public String getValue() { 
     return ((Interface1)targetSource.getTarget()).execute(); 
    } 

    @Required 
    public void setConfigurationKey(String key) { 
     this.key = key; 
    } 

    @Required 
    public void setSwappableBeans(Map<String, T> swappableBeans) { 
     this.swappableBeans = swappableBeans; 
    } 

} 

和bean聲明應該如下:

<bean id="Interface1Swappable" class="path.to.CustomSwappable"> 
     <property name="configurationKey" value="swappableKey"/> 
     <property name="swappableBeans"> 
      <util:map value-type="path.toInterface1"> 
       <!-- first is default --> 
       <entry key="classA"> 
        <bean class="path.to.class.A"/> 
       </entry> 
       <entry key="classB"> 
        <bean class="path.to.class.B"/> 
       </entry> 
      </util:map> 
     </property> 
    </bean> 
+0

感謝您的信息。我有2個錯誤..一個是「SampleService」給出錯誤。我們是否還需要在界面中定義「configChanged」? – Dev

+0

@Dev關於第一個問題,您應該將其替換爲'Interface1'而不是SampleService。 'configChanged'不應該被覆蓋,我的錯誤。考慮這個代碼作爲演示樣本。實際的實施應該根據你的需要來完成。 – hahn

+0

謝謝。在運行時,我將如何將實現從ClassA更改爲ClassB。請讓我知道... – Dev