首先我们先来看@Autowired这个注解是怎么使用的?
先准备好测试代码:
//service接口
public interface TestService {
public void testHello();
}
//service实现类 (暂时只有一个实现类)
@Service
public class TestServiceImpl1 implements TestService {
@Override
public void testHello() {
System.out.println("say hello 11111");
}
}
//测试类 使用的是
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@WebAppConfiguration
public class TestDemo {
@Autowired
TestService testService;
@Test
public void test(){
testService.testHello();
}
}
执行后输出结果:
say hello 11111
按照正常流程,我们的结果符合预期,那么@Autowired 是怎么注入的呢?
当我们使用@Autowired的注解的时候,容器会通过testService的类型去找到对应的bean,然后注入,因为只有TestServiceImpl1实现了TestService这个接口,所以只能注入TestServiceImpl1这个bean。
如果我们再新建一个TestServiceImpl2也实现TestService接口呢?