spring 将接口实现类注入Map

spring本身会自动将接口的实现类直接@Autowired注入Map,list等集合中,无需作任何配置。直接上代码。

接口类:

public interface Pepole {
	
	String say();
}

实现类有三个:

@Component
public class Britisher implements Pepole {

	@Override
	public String say() {
		return "helloword";
	}

}

@Component
public class Chinese implements Pepole {

	public String say() {
		return "你好";
	}

}


@Component
public class French implements Pepole {

	@Override
	public String say() {
		return "french";
	}
}

测试代码:

@RestController
public class MainController {

	@Autowired
	MyApplicationContext ctx;
	
	@Autowired
	Map<String,Pepole> map;
	
	@GetMapping("/hi")
	public String say() {
		ApplicationContext context = ctx.getApplicationContext();
		
		Pepole ese = (Pepole) context.getBean("chinese");
		System.out.println(ese.say());
		Pepole esex = (Pepole) context.getBean("britisher");
		System.out.println(esex.say());
		Pepole esef = (Pepole) context.getBean("french");
		System.out.println(esef.say());
		return "成功";
	}
}

注意一点Map的Key是类名首字母小写。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章