Spring @Autowired Map

本文介绍了Spring框架如何自动将Bean注入到Map和List中,详细解析了注入过程以及如何通过@Order注解来控制List中Bean的注入顺序。示例代码展示了CheckStrategy接口的两个实现类,以及在Test类中如何使用@Autowired注解从Map和List中获取并调用这些Bean。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有时候在代码中看到Map或List类型的注入
在这里插入图片描搜索述
这是spring的特殊用法,Spring 会将容器中所有类型符合 Map 的 value 对应的类型的 Bean 增加进来,用 Bean 的 id 或 name 作为 Map 的 key。
或者

@Autowried
private List<CheckStratedy> list;

当注入一个Map的时候 ,value泛型为CheckStrategy,则注入后Spring会将实例化后的bean放入value ,key则为注入后bean的名字

当注入一个List的时候,List的泛型为CheckStrategy,则注入后Spring会将实例化的bean放入List中

例如:

package com.service;

public interface CheckStrategy {

    void check();
}

实现类:

package com.service.impl;

import com.service.CheckStrategy;
import org.springframework.stereotype.Component;

@Component
public class CheckValue implements CheckStrategy {
    @Override
    public void check() {
        System.out.println("11111");
    }
}

package com.service.impl;

import com.service.CheckStrategy;
import org.springframework.stereotype.Component;

@Component
public class CheckKey implements CheckStrategy{
    @Override
    public void check() {
        System.out.println("222");
    }
}

package com.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
public class Test {

    @Autowired
    private Map<String,CheckStrategy> checkStrategy;

    @Autowired
    private List<CheckStrategy> checkStrategyList;



    public void  sendMap(){
        this.checkStrategy.get("checkValue").check();  // 11111
    }

/**
Spring将bean放入了List中 那个这个顺序怎么控制呢

在实现类上加入@Order(value) 注解 ,值越小越先被放入List
**/
     public void  sendList(){
        this.checkStrategyList.get(0).check(); // 1111
    }
}


Spring将bean放入了List中 那个这个顺序怎么控制呢

在实现类上加入@Order(value) 注解 ,值越小越先被放入List

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值