I have the following setup:
@Component public class ImplOne implements IFace{ } @Component public class ImplTwo implements IFace{ } public interface IFace{ } I am trying to get a reference of ImplOne by type:
@RunWith(SpringJUnit4ClassRunner.class) public class ImplOneTest { @Autowired private ImplOne impl; @Test public void test(){ Assert.assertNotNull(impl); } } Though with this I get the following exception:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [some.package.TestBean] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations {@org.springframework.beans.factory.annotation.Autowired(required=true)} I tried the following workarounds:
- Remove "implements IFace" from ImplOne so the implementation class itself gets Proxied by cglib. Not acceptable because I also need to be able to get all implementations of IFace in my application code.
- Doing method injection via a @Autowired public void setImplOne(IFace[] beans) and filtering the instance through instanceof check does not work, because the injected beans are subclasses of type java.lang.reflect.Proxy which doesn't offer any useful methods.
- Changing @Component of ImplOne to @Component("implone") and using @Qualifier("implone").
Code:
@RunWith(SpringJUnit4ClassRunner.class) public class ImplOneTest { @Autowired @Qualifier("implone") private ImplOne impl; @Test public void test(){ Assert.assertNotNull(impl); } } But I don't like the idea of having to name my beans just to be able to inject the concrete implementation.
Is there some way to do this elegantly, or atleast in some manner that only affects my test code? Also is there some special reason why my first example is unsupported?
@Qualifierand it didn't work. I even have just one concrete implementation.@Qualifieris only used to resolve ambiguity if there's any, otherwise it would be ignored. Therefore using@Qualifierdoesn't make any difference unless you have more than one implementation. I wonder how could you possibly make it work since the problem is not ambiguity but simply there's no even a bean with the specified matching type.