1

Consider a code:

public class MyProcessor<T extends GenericData> implements ProcessorInterface<T> {

    @Autowired
    private List<SomeCriteria<T>> criterias;

    @Override
    public long calculate(T data) {
        long result = 0;
        for (SomeCriteria c : criterias) {
            result += c.calculate(data);                        
        }
        return long;         
    }
}

So the difference only in SomeCriteria implementation and GenericData. E.g. for one GenericData there are several SomeCriteria. So if there are 3 GenericData is it possible to write a code like that:

public DataService {
    @Autowire
    private MyProcessor<DataOne> processorOne;
    @Autowire
    private MyProcessor<DataTwo> processorTwo;
    @Autowire
    private MyProcessor<DataThree> processorThree;
}

Without writing implementation for processor each time?

bummi
  • 27,123
  • 14
  • 62
  • 101
Cherry
  • 31,309
  • 66
  • 224
  • 364

2 Answers2

2

Yes, it is possible. As of Spring 4.0 you can do thing such as

@Autowired
private Store<String> s1; // Injects the stringStore bean

@Autowired
private Store<Integer> s2; // Injects the integerStore bean

The example above was copied from the Spring Framework 4.0 and Java Generics blog post by Phil Webb on the Spring web site. Please read it for more details.

matsev
  • 32,104
  • 16
  • 121
  • 156
  • I see, but if `Store` has dependecies like `Item`, will Spring inject `Item` into Store when Store autowired like `@Autowired Store`? – Cherry Feb 07 '16 at 03:04
1

You can use @Qualifier annotation for create more than one bean of the same type. I hope this will helpfull to you.

public DataService {
    @Qualifier
    private MyProcessor<DataOne> processorOne;
    @Qualifier
    private MyProcessor<DataTwo> processorTwo;
   }
Niks
  • 175
  • 7
  • It is not necessary to use the `@Qualifier` annotation to get generic support, see my answer (or preferably read the blog post about [Spring Framework 4.0 and Java Generics](https://spring.io/blog/2013/12/03/spring-framework-4-0-and-java-generics). – matsev Feb 06 '16 at 21:23