2016-11-21 71 views
2

比方說,我有以下bean定義Spring是否會自動在java bean定義中自動構造autowire參數?

@Bean 
public Beehive beehive(ArrayList<Bee> bees) { 
    return new Beehive(bees); 
} 

@Bean 
public ArrayList<Bee> bees() { 
    return new ArrayList<Bee>(); 
} 

將在beehive bean方法的bees可以在自動裝配?

我在問,因爲我沒有使用@Autowired註釋來表現這樣的應用程序,並且要確保我理解正在發生的事情。

+1

我相信是的。如果他們在同一個類中,使其更加明確的一個好方法是簡單地使用'return new Beehive(bees());'。然後arg可以從'beehive' bean方法中移除。 – CollinD

+0

您應該在方法簽名中使用'List'而不是'ArrayList'。 –

+0

@EngineerDollery但如果我想確保只有'ArrayList'被用來保持蜜蜂? – zero01alpha

回答

2

Spring是否會自動在java bean定義中自動構造Autowire參數?

是的,它的確如此。你可以參考Spring文檔中的here,我在下面添加(強調我的)。

甲@Bean註解的方法可以具有參數描述 構建豆所需的依賴關係的任意的數。例如 如果我們TransferService需要AccountRepository我們可以 兌現是通過方法參數的依賴:

@Configuration 
public class AppConfig { 
    @Bean 
    public TransferService transferService(AccountRepository accountRepository) { 
     return new TransferServiceImpl(accountRepository); 
    } 
} 

的解決機制是幾乎相同的構造器 依賴注入

相關問題