Java Spring 注解问题
我对春天有疑问。我正在用基于注释的配置替换基于 xml 文件的 spring 配置。因此我遇到了以下问题。有一个类,其中一个字段是通过基于类的自动装配来配置的。迄今为止,只有一名候选人。但现在有不止一个候选者,因为我已将 @Named 标记添加到同一接口的多个类中。
这是一个代码示例: 具有自动装配字段的类:
public class AutowiringClass<X, Y> {
// This is the field which is autowired
private Autowired<X, Y> bean;
.....
}
然后是第二个类,它使用特定的泛型参数扩展 AutoWiringClass:
public class TestClass extends AutoWiringClass<ObjectX, ObjectY> {
.....
}
问题是,spring 不知道它应该使用哪个类,因为有多个 Autowiring 类型的类,但是具有不同的泛型类型(ObjectX、ObjectY)。我认为,不同的泛型类型可以做到这一点..但他们没有:( 如果有人能找到解决方案,那就太棒了。
I've a problem with spring. I'm replacing the xml file based configuration of spring with annotation based configuration. Because of that I runned into the following problem. Theres is a class, where one field is configured by class based autowiring. Since yet, there has been only one candidate. But now there is more then one candidate, because I've added the @Named tag to mutliple classes of the same interface.
Here is a code example:
The class with the autowiring field:
public class AutowiringClass<X, Y> {
// This is the field which is autowired
private Autowired<X, Y> bean;
.....
}
Then there is a second class, which extends AutoWiringClass with specific generic arguments:
public class TestClass extends AutoWiringClass<ObjectX, ObjectY> {
.....
}
The Problem is, that spring doesn't know which class it should use, since there are more than once class of the type Autowiring but with different generic types (ObjectX, ObjectY). I thought, that the different generic types will do the thing.. but they doesn't :(
It would be awesome if anybody has an solution for that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
限定符是什么你正在寻找。当您将一个类注册为 Spring bean(使用 @Component 等)时,您可以将名称作为参数传递。然后,当您自动装配属性时,添加带有该 bean 名称的
@Qualifier
注释。所以:Qualifiers are what you are looking for. When you register a class as a Spring bean (using
@Component
or the like) you can pass a name as an argument. Then when you are autowiring a property, add a@Qualifier
annotation with that bean's name. So:由于类型擦除,泛型不会帮助你,Spring对此无能为力。但是您可以使用 @Primary 注释来表示应始终使用的默认实现,或者切换到按名称而不是按类型自动装配。然后 Spring 在有疑问时将使用字段名称。
Generics won't help you due to type erasure, Spring can't do nothing about it. But you can either use
@Primary
annotation to denote the default implementation that should be always used or switch to autowiring by name rather than by type. Then Spring will use field name when in doubt.