Spring getBean with type validation

我只是一个虾纸丫 提交于 2019-12-18 21:12:52

问题


I'm using the method ApplicationContext.getBean(String name, Class requiredType). The bean is of type util:set. My code looks like:

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

I want to know is how to do something like this to avoid the type casting warning:

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

I'm not sure if it's possible to define the type of a class in this way. Am I dreaming or is there a way to do this?

Thanks.


回答1:


Not really but there is a runtime workaround that at least removes the need for an @SuppressWarnings. You can make your class abstract and let Spring instrument your code:

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

and then inject a lookup method in your XML config:

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

It's not really statically checked but it fails-fast at runtime and you keep the ugly casting out of your code.




回答2:


maybe this can be usefull to you:

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



来源:https://stackoverflow.com/questions/5266127/spring-getbean-with-type-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!