【问题标题】:Spring getBean with type validation具有类型验证的 Spring getBean
【发布时间】:2011-03-10 21:27:42
【问题描述】:

我正在使用方法 ApplicationContext.getBean(String name, Class requiredType)。 bean 的类型为 util:set。我的代码如下:

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

我想知道如何做这样的事情来避免类型转换警告:

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

我不确定是否可以以这种方式定义类的类型。我是在做梦还是有办法做到这一点?

谢谢。

【问题讨论】:

    标签: spring generics casting


    【解决方案1】:

    并非如此,但有一个运行时解决方法至少可以消除对@SuppressWarnings 的需求。您可以将您的类抽象化并让 Spring 检测您的代码:

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

    然后在您的 XML 配置中注入 lookup method

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

    它不是真正静态检查的,但它在运行时会快速失败,并且您可以避免丑陋的代码转换。

    【讨论】:

      【解决方案2】:

      也许这对你有用:

      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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-05-21
        • 2021-04-01
        • 2017-03-27
        • 1970-01-01
        • 2022-08-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多