Are the rules/behaviors around @Autowired
different when writing tests? It seems that with a test, you can autowire to a concrete type, but if you try the same thing inside a @Component
it will fail. This is a contrived example, but it's something I ran into and am just trying to understand better.
Contrived example code:
public interface Gizmo {
void whirr();
}
@Configuration
public class GizmoConfiguration {
@Bean
@Profile("no-dependencies")
public Gizmo fooGizmoBean() {
return new FooGizmo();
}
@Bean
@Profile("!no-dependencies")
public Gizmo barGizmoBean() {
return new BarGizmo();
}
public class FooGizmo implements Gizmo {
@Override
public void whirr() {
}
}
public class BarGizmo implements Gizmo {
@Override
public void whirr() {
}
}
}
Test that runs fine:
@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles(Application.Profiles.NO_DEPENDENCIES)
public class TestClass {
@Autowired
private GizmoConfiguration.FooGizmo gizmo;
@Test
public void test() {
assertNotNull(gizmo);
}
}
Component that causes java.lang.IllegalStateException: Failed to load ApplicationContext
:
@Component
public class TestComponent {
@Autowired
private GizmoConfiguration.FooGizmo gizmo;
}
because of:
No qualifying bean of type 'GizmoConfiguration$FooGizmo' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}