我正在使用方法 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);
我不确定是否可以以这种方式定义类的类型。我是在做梦还是有办法做到这一点?
谢谢。
最佳答案
并非如此,但有一个运行时解决方法至少可以消除对@SuppressWarnings 的需求。您可以将您的类抽象化并让 Spring 检测您的代码:
public abstract class Test {
Set<String> getMyBean();
}
然后注入(inject) lookup method在您的 XML 配置中:
<bean class="Test">
<lookup-method name="myBean" bean="myBean" />
</bean>
它不是真正静态检查的,但它在运行时会快速失败,并且您可以将丑陋的代码排除在外。
关于具有类型验证的 Spring getBean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5266127/