Spring @Autowired Map 和 List

在开发的时候有时候经常会看到这样代码


这是Spring的一个特殊的注入功能

如图所示

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

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

做个测试

首先定义一个接口

package com.service;

public interface MaoService {

void say();
}

然后定义三个MaoService的实现类 Fish 、Dog、 Cat

package com.service.impl;

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

@Component
public class Fish implements MaoService {
@Override
public void say() {
System.out.println("xuxuxu");
}
}
package com.service.impl;

import com.service.MaoService;
import org.springframework.stereotype.Component;
@Component
public class Dog implements MaoService {
@Override
public void say() {
System.out.println("汪汪汪");
}
}
package com.service.impl;

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

@Component
public class Cat implements MaoService {
@Override
public void say() {
System.out.println("喵喵喵");
}
}

在编写一个测试类

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,MaoService> maoServiceMap;

@Autowired
private List<MaoService> maoServiceList;



public void sendMap(){
this.maoServiceMap.get("cat").say();
}

public void sendList(){
this.maoServiceList.get(0).say();
}
}

然后使用SpringTest

package com;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class TestApplicationTests {

@Autowired
private com.service.Test maoService;
@Test
public void sayMap(){
this.maoService.sendMap();
}

@Test
public void sayList(){
this.maoService.sendList();
}

}

DeBug进去看看

Map的key为bean的名字 value是bean的实例

紧接着为List

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

在实现类中加入@Order(value) 注解即可 ,值越小越先被初始化越先被放入List