一、原理
以service的name作为key,value为同类型的产品service实现方式
二、demo
1、定义接口
package mytest.service;
public interface AnimalService {
void said();
}
2、不同产品实现方式
1) Dog
package mytest.service;
import org.springframework.stereotype.Service;
@Service("dog")
public class DogService implements AnimalService {
@Override
public void said() {
System.out.println("I am a dog");
}
}
2) cat
package mytest.service;
import org.springframework.stereotype.Service;
@Service("cat")
public class CatService implements AnimalService {
@Override
public void said() {
System.out.println("I am a cat");
}
}
3、注入使用
package mytest.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
@Service
public class ZooServiceImpl implements ZooService{
private Map<String, AnimalService> animalMap;
@Autowired
public ZooServiceImpl(Map<String, AnimalService> animalMap) {
this.animalMap = animalMap;
}
@Override
public void introduce(String name) {
animalMap.get(name).said();
}
}
可以看到,根据传入的name名字即可调用对应的服务,name即为service注解中的value值