Last active
January 17, 2019 07:17
-
-
Save shiyifan/dfee06672adec338ba34ca32fb1d2c3e to your computer and use it in GitHub Desktop.
当Spring依据“类型匹配(type-matching)”规则找到注入点(Injection Point)(例如:randomer)的多个候选Bean时,Spring会查找与注入点的变量名相同的Bean的Name属性,如果找到一个则进行注入,否则抛出异常。See Alsohttps://docs.spring.io/spring/docs/5.1.4.RELEASE/spring-framework-reference/core.html#beans-autowired-annotation-qualifiers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Component("indexRandomer") | |
public class IndexRandomer implements Randomer { | |
@Override | |
public List<Integer> nextIntList(int bound, int length) { | |
List<Integer> list = IntStream.range(0, bound).collect(ArrayList::new, ArrayList::add, ArrayList::addAll); | |
Random rnd = new Random(); | |
List<Integer> result = new ArrayList<>(length); | |
for (int i = 0; i < length; i++, bound--) { | |
int idx = rnd.nextInt(bound); | |
result.add(list.get(idx)); | |
list.remove(idx); | |
} | |
return result; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Component | |
public class LoginController { | |
private Randomer randomer; | |
/*此处的注入点为构造器的shuffleRandomer变量,虽然依据type-matching规则查询到两个具体Bean:shuffleRandomer和indexRandomer,但是随后Spring | |
依据变量名与两个候选Bean的Name匹配得出匹配结果为shuffleRandomer。如果将该shuffleRandomer变量名改写为randomer,则会抛出运行时异常。 | |
对于一个注入点存在多个候选Bean的情况,可以使用@Primary注解,@Qualifier注解以及变量名与Bean Name匹配的机制进行精确注入*/ | |
@Autowired | |
public LoginController(Randomer shuffleRandomer) { | |
this.randomer = shuffleRandomer; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Component("shuffleRandomer") | |
public class ShuffleRandomer implements Randomer { | |
@Override | |
public List<Integer> nextIntList(int bound, int length) { | |
List<Integer> list = IntStream.range(0, bound).collect(ArrayList::new, ArrayList::add, ArrayList::addAll); | |
Collections.shuffle(list); | |
return list.subList(0, length); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment