Spring getBean类型验证 [英] Spring getBean with type validation

查看:147
本文介绍了Spring getBean类型验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的方法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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆