Consider following configuration with two beans of the same type created:
@Configuration
@ComponentScan(basePackageClasses = TwoStrings.class)
public class Config {
@Bean
public String one() {
return "one";
}
@Bean
public String two() {
return "two";
}
}
Another bean that depends on the two beans above is created by component scan:
@Component
public class TwoStrings {
public final String a;
public final String b;
@Autowired
public TwoStrings(String one, String two) {
this.a = one;
this.b = two;
}
}
The names of local variables/parameters are lost during compilation and are not available at runtime:
However, Spring somehow autowires two String
beans correctly. The example test below
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Config.class )
public class Example {
@Autowired
private TwoStrings twoStrings;
@Test
public void test() {
System.out.println(twoStrings.a);
System.out.println(twoStrings.b);
}
}
prints
one
two
Given the name of constructor parameters are lost, I would expect Spring to throw the exception saying that there is more than 1 bean of type String
, however Spring somehow autowires beans using parameters names.
The question is how Spring knows the names of constructor parameters?
Aucun commentaire:
Enregistrer un commentaire