平常业务中一般都是单实现类,最近研究下了一个接口多实现的用途
1.定一个接口(案例)
public interface PersonService {
void doWork();
}
2.两个(或多个)实现,具体实现的方法体不同;
@Service("studentService")
public class StudentServiceImpl implements PersonService {
@Override
public void doWork() {
System.err.println(“ studying");
}
}
——————————
@Service("teacherService")
public class TeacherServiceImpl implements PersonService {
@Override
public void doWork() {
System.err.println("teaching");
}
}
- 调用接口时@autowire注入
@RunWith(SpringRunner.class)
@SpringBootTest
public class Testff {
@Autowired
private PersonService personService;
}
idea会提示
Could not autowire. There is more than one bean of ‘PersonService’ type.
Beans:
studentService (StudentServiceImpl.java)
teacherService (TeacherServiceImpl.java)
重点来了,有几种方式<