带有类型验证的Spring getBean

Pau*_*aul 11 generics spring casting

我正在使用方法ApplicationContext.getBean(String name,Class requiredType).bean的类型为util:set.我的代码看起来像:

Set<String> mySet = context.getBean("myBean", Set.class);
Run Code Online (Sandbox Code Playgroud)

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

Set<String> mySet = context.getBean("myBean", Set<String>.class);
Run Code Online (Sandbox Code Playgroud)

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

谢谢.

小智 3

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

public abstract class Test {
  Set<String> getMyBean();
}
Run Code Online (Sandbox Code Playgroud)

然后在 XML 配置中注入一个查找方法:

<bean class="Test">
  <lookup-method name="myBean" bean="myBean" />
</bean>
Run Code Online (Sandbox Code Playgroud)

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