Spring getBean类型验证 [英] Spring getBean with type validation
问题描述
我使用的方法ApplicationContext.getBean(String name,Class requiredType)。 bean是util:set类型。我的代码如下:
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?
谢谢。
推荐答案
不是真的,但有一个运行时解决方法,至少删除了@SuppressWarnings的需要。你可以让你的类抽象,让Spring用你的代码:
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();
}
,然后注入查找方法:
<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.
这篇关于Spring getBean类型验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!