我有一个非常简单的spring引导测试应用程序。
它只有一个Dog类和@SpringBootApplication注释类。我创建了两个Dog的bean,一切都按预期运行。
public class Dog {
public String name;
public Dog() {
this("noname");
}
public Dog(String name) {
this.name = name;
}
public String toString() {
return name;
}
}
@SpringBootApplication
public class DemoApplication {
@Autowired
private List<Dog> dogs;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
CommandLineRunner runner1() {
return args -> {
for (Dog d : dogs) {
System.out.println(d);
}
};
}
@Bean
Dog laika() {
return new Dog("laika");
}
@Bean
Dog lassie() {
return new Dog("lassie");
}
}
输出:
laika
lassie
但是,现在我向Dog类添加了一个@Component注释,预计现在我会得到三个类型为Dog的bean,如果我用另一个这样的CommandLineRunner打印所有bean,就会发生这种情况:
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
return args -> {
System.out.println("Let's inspect the beans provided by Spring Boot:");
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
System.out.println(beanName);
}
};
}
输出:
Let's inspect the beans provided by Spring Boot:
applicationAvailability
applicationTaskExecutor
commandLineRunner
demoApplication
dog
laika
lassie
lifecycleProcessor
...
然而,当我使用我的第一个CommandLineRunner输出我的狗列表的内容时,我得到的唯一输出是:
noname
似乎@Component Bean已经使@Bean声明的Bean失效,以进行集合注入。我观察到任何bean都有相同的行为,例如,如果我在一个独立的@Component类中声明更多的组件,每个人都会运行,但当我在列表中@Autowire它们时,只有用@ CommandLineRunners声明的组件才会被注入。
然而,我仍然可以使用其他的Dog beans。例如,如果我用@Primary注释Laika bean,它将被作为方法参数注入,但关于@Autowire'd集合没有任何变化。
发布于 2020-12-09 00:35:59
您的引导应用程序很有趣,但不管怎样,这台pcs上的代码
@Bean
CommandLineRunner runner1() {
return args -> {
for (Dog d : dogs) {
System.out.println(d);
}
};
}
当它被调用时,另外两个狗还没有初始化,所以在狗列表中只有一个@component注解的狗,它是"noname“
https://stackoverflow.com/questions/65202571
复制相似问题