SpringBoot中 使用@Autowired 将bean注入到List或Map等集合中

在SpringBoot开发中,当一个接口A有多个实现类时,spring会很智能的将bean注入到List<A>或Map<String,A>变量中。

一、将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<IPerson> persons;

	@Autowired
	Map<String, IPerson> personMaps;

	public void echo() {
		System.out.println("print list:");
		for (IPerson p : persons) {
			p.doWork();
		}

		System.out.println("\nprint map:");
		for (Map.Entry<String, IPerson> 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<String, IPerson> 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")来调用不同的实现类,即达到设计模式中策略模式的类似效果。

  • 24
    点赞
  • 59
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
@Autowire标注作用于Map类型时,Spring会将容器所有类型符合Map的value对应的Bean增加进来,并以Bean的id或name作为Map的key。具体来说,当使用@Autowired注解注入一个Map类型的属性时,Spring会自动将所有符合Map value类型的Bean注入到这个Map,以Bean的id或name作为Map的key。例如,在上述的示例,Demo类的setA方法和setB方法都使用@Autowired注解注入Map类型的参数,Spring会将所有类型为A的Bean注入到aMap,将所有类型为B的Bean注入到bMap。这样,我们就可以通过aMap和bMap来获取对应的Bean实例了。 #### 引用[.reference_title] - *1* [使用@Autowired对set方法参数是map注入](https://blog.csdn.net/qq_36997245/article/details/105061279)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [@Autowired自动注入map](https://blog.csdn.net/AttleeTao/article/details/126034525)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [SpringBoot 使用@Autowiredbean注入ListMap集合](https://blog.csdn.net/inrgihc/article/details/104742206)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值