0

My interface

public interface IProcessContextFactory<U, T> {   
    public IProcessContext<U> createContext(T data);  
}

@Component("PricingProcessContextFactory")
public class PricingProcessContextFactory implements IProcessContextFactory<OrderEntity, OrderEntity> {

   @Override
   public IProcessContext<OrderEntity> createContext(final OrderEntity data)
   {
            ..........
   }      
 }

Now if i inject like this spring says Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [......IProcessContextFactory]

@Autowired
@Qualifier(value = "PricingProcessContextFactory")
private IProcessContextFactory<Object, Object> processContextFactory;

I would like to know what will be the correct way. Any ideas.?

Saurabh Kumar
  • 16,353
  • 49
  • 133
  • 212

1 Answers1

0

In Spring 4 it is possible to autowire by parameter types declaration. There is no need for qualifier if you use interface with Generics:

@Autowired
private IProcessContextFactory<OrderEntity, OrderEntity> processContextFactory;

This is the least possible coupling as you could add mock implementation with the same parameters and autowire mock instead. With the qualifier, there is direct dependency on specific bean with a given name. As another thing to consider, you would have to cast to OrderEntityexplicitly and that sort of kills the point of parameterized interface.

However, you can also do it with qualifier and concrete type, but that is reudndant:

@Autowired
@Qualifier("PricingProcessContextFactory")
private IProcessContextFactory<OrderEntity, OrderEntity> processContextFactory;

As to why your example doesn't work, although it looks like it should, i will give you my best guess, but i cannot back this up with some source.

Imagine if you had two implementations of Generic interface, and each of these implementations are @Service with some name and data types.

When you autowire implementation of Generic interface parameterized with Object, Spring has two possible candidates for implementation. The only way for Spring to know which bean to inject here would be by the qualifier name.

Since there is already mechanism to resolve Generic interface implementations by type, existence of qualifier would have to be prioritized and used instead of type declarations. But since the autowire by data type declaration offers much lower coupling, and this is how it is documented that should be used on Spring site, i guess autowiring of implementation with object parameter types is not supported as it is inferior option.

Spring Autowiring Generics

John
  • 5,189
  • 2
  • 38
  • 62