簡體   English   中英

@Component bean 覆蓋 @Bean 用於集合自動裝配

[英]@Component beans override @Bean ones for collection autowiring

我有一個非常簡單的 spring 啟動測試應用程序。

它只有一個 Dog class 和 @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 class 添加了一個 @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 打印出我的 Dog 列表的內容時,我得到的唯一 output 是:

noname

似乎@Component bean 已經使 @Bean 聲明的 bean 消失以進行集合注入。 我觀察到任何 bean 的相同行為,例如,如果我在獨立的 @Component class 中聲明更多 CommandLineRunners,每個人都會運行,但是當我在列表中 @Autowire 時,只有使用 @Component 聲明的那些被注入。

盡管如此,我仍然可以使用其他狗豆。 例如,如果我用 @Primary 注釋 Laika bean,它將作為方法參數注入,但 @Autowire 的集合沒有任何變化。

您的啟動應用程序以一種有趣的方式,但無論如何,這段代碼

    @Bean
CommandLineRunner runner1() {
    return args -> {
        for (Dog d : dogs) {
            System.out.println(d);
        }
    };
}

調用時,其他 2 只狗尚未初始化,因此在狗列表中,您只有 @component 注釋的一只,即“noname”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM