Spring if there are multiple implementations of the Service class, how do you know which category ServiceImpl the injection?

1. Each service impl can specify the name (using @Service ( "name"))

When injected into the service of 2.Controller use the name to specify which one injection.

  (1).

  @Autowired
@Qualifier("名称") 

  (2).

  @Resource (name = " name" )

 

code show as below:

interface
public interface HumanService {
public String name();
}
Interface implementation class 
@Service("teacherService")
public class TeacherServiceImpl implements HumanService {
@Override
public String name() {
System.out.println("teacher");
return "teacher";
}
}
 
 
@Service("doctorService")
public class DoctorServiceImpl implements HumanService {
@Override
public String name() {
System.out.println("doctor");
return "doctor";
}
}
Controller 

@RestController
public class HumanController {
// @Resource(name="doctorService")
    @Autowired
@Qualifier("teacherService")
private HumanService humanService;

@RequestMapping("/name")
public String name(){
return humanService.name();
}
}
 

 

Guess you like

Origin www.cnblogs.com/zoe-java/p/11530888.html