1

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.

2 Answers 2

3

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

No thats not I'm looking for. Sorry, I should had mentioned that, but I forogt. The problem is, that there are multiple TestClasses, that are extending AutoWiringClass. But in this TestClass the generics of the AutoWiringClass are different, but Java doesn't notice it :( And in the future there will be new TestClasses, but the Programmer of the TestClass should not care about setting the variable about a Qualifier, I hope there is a way to realize that.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.