2011-03-10 69 views
10

我使用ApplicationContext.getBean(String name,Class requiredType)方法。該bean是util:set類型的。我的代碼如下所示:類型驗證的Spring getBean

Set<String> mySet = context.getBean("myBean", Set.class); 

我想知道的是如何做這樣的事情,以避免類型轉換警告:

Set<String> mySet = context.getBean("myBean", Set<String>.class); 

我不知道,如果是可以定義的類型以這種方式上課。我在做夢還是有辦法做到這一點?

謝謝。

回答

3

不是真的,但有一個運行時變通辦法,至少可以消除對@SuppressWarnings的需求。你可以讓你的抽象類,讓春天的儀器代碼:

public abstract class Test { 
    Set<String> getMyBean(); 
} 

,然後在你的XML配置注入lookup method

<bean class="Test"> 
    <lookup-method name="myBean" bean="myBean" /> 
</bean> 

這不是真的靜態檢查,但在失敗快運行時,並保持醜陋的你的代碼。

1

也許這可能是有用的你:

Set<String> setBean= null; 
Map<String, Set> beans = applicationContext.getBeansOfType(Set.class); 
for (Map.Entry<String, Set> bean: beans.entrySet()) { 
    ParameterizedType thisType = (ParameterizedType) bean.getClass().getGenericSuperclass(); 
    Class<?> parametrizedClass= thisType.getActualTypeArguments()[0]; 
    if (parametrizedClass.isAssignableFrom(String)) { 
     setBean= (Set<String>) bean; 
    } 
} 

http://javahelp.redsaltillo.net