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是類名首字母小寫。

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