在SpringBoot开发中,当一个接口A有多个实现类时,spring会很智能的将bean注入到List或Map
举例说明如下:
步骤1:定义一个接口
public interface IPerson {
void doWork();
}
步骤2:对该接口做第一个实现类
import org.springframework.stereotype.Component;
@Component("student")
public class StudentImpl implements IPerson {
@Override
public void doWork() {
System.out.println("I am studying");
}
}
步骤3:对该接口做第二个实现类
import org.springframework.stereotype.Component;
@Component("teacher")
public class TeacherImpl implements IPerson {
@Override
public void doWork() {
System.out.println("I am teaching");
}
}
步骤4:使用@Autowired对List和Map进行注入使用
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class PersonService {
@Autowired
List persons;
@Autowired
Map personMaps;
public void echo() {
System.out.println("print list:");
for (IPerson p : persons) {
p.doWork();
}
System.out.println("\nprint map:");
for (Map.Entry entry : personMaps.entrySet()) {
System.out.println("Person:" + entry.getKey() + ", " + entry.getValue());
}
}
}
步骤5:编写启动类调用PersonService的echo()函数进行测试
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication springApplication = new SpringApplication(Application.class);
ApplicationContext context=springApplication.run(args);
PersonService service=context.getBean(PersonService.class);
service.echo();
}
}
程序运行结果为:
print list:
I am studying
I am teaching
print map:
Person:student, com.tang.aaa.StudentImpl@723e88f9
Person:teacher, com.tang.aaa.TeacherImpl@5f0fd5a0
对应Map的注入,key必须为String类型,即bean的名称,而value为IPerson类型的对象实例。
通过对上述Map类型的注入,可以改写为根据bean名称,来获取并使用对应的实现类。
举例如下:
步骤1:修改上述步骤4中的PersonService类如下:
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class PersonService {
@Autowired
Map personMaps;
public void work(String name) {
IPerson person=personMaps.get(name);
if(null!=person) {
person.doWork();
}
}
}
步骤2:通过对PersonServer的work()传递不同的参数,实现对不同实现类的调用
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication springApplication = new SpringApplication(Application.class);
ApplicationContext context=springApplication.run(args);
PersonService service=context.getBean(PersonService.class);
service.work("teacher");
}
}
我们可以使用service.work("teacher")或者service.work("student")来调用不同的实现类,即达到设计模式中策略模式的类似效果。