简体   繁体   中英

How to set Qualifier on an Implementation that has an interface which extends another interface

I have 2 Interfaces A and B which extends another Interface C. However when i use the @Qualifier("aImpl") i get a unsatisfactionary dependency from spring

The interfaces

public interface EsResourceLoader { ... }

public interface CommonEsDao extends EsResourceLoader { ... }

public interface CommonModifiedEsDao extends EsResourceLoader { ... }

The first implementation

@Service
public class LBModifiedEsDao implements CommonModifiedEsDao { ... }

The second implementation

@Service
public class LBDao implements CommonEsDao { 

  private CommonModifiedEsDao myDao;

  @Autowired
  public LBDao(@Qualifier("lBModifiedEsDao") CommonModifiedEsDao myDao) { ... 
  }
}

The controller throwing the exception

@RestController
@RequestMapping{...}
public class IndexAdminController {

  private CommonEsDao esDao;

  @Autowired
  public IndexAdminController(@Qualifier("lBDao")CommonEsDao esDao){ ... }


}

And here is the Exception

Exception encountered during context initialization - cancelling refresh 
attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: 
Error creating bean with name 'indexAdminController': Unsatisfied dependency 
expressed through field 'lbDao';

Put your @Qualifier annotation to service and it should works.

@Service
@Qualifier("lBModifiedEsDao") 
public class LBModifiedEsDao
implements CommonModifiedEsDao { ... }

And also for second service

@Service
@Qualifier("lBDao")
public class LBDao implements CommonEsDao { 

  private CommonModifiedEsDao myDao;

  @Autowired
  public LBDao(@Qualifier("lBModifiedEsDao") CommonModifiedEsDao myDao) { ... 
  }
}

Now Spring should be able to always autowire it correctly. Also this is also nice because you can be sure with that you will have always correct implementation.

EDIT: As I did in your code with @Qualifier annotation can be achieved by using name in Component annotations, ie.: @Component("myComponent")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM