开发者

Java Spring Problem with annotations

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 开发者_如何学Goautowiring. 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.


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:

@Component("Test1")
public class Test { }
@Component("Test2")
public class BetterTest extends Test {}

public class TestUser {
  @Autowired
  @Qualifier("Test1")
  private Test test;
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜