Spring getBean with type validation

后端 未结 2 401
南笙
南笙 2021-01-04 12:49

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

Set mySe         


        
相关标签:
2条回答
  • 2021-01-04 13:15

    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.

    0 讨论(0)
  • 2021-01-04 13:18

    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

    0 讨论(0)
提交回复
热议问题