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是类名首字母小写。

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值