配置Bean注意事項(xiàng)

當(dāng)配置類中只有一個(gè)該類型Bean時(shí),在注入的時(shí)候。其名字隨意。例如:

@Configuration
public class ComputerConfig {

    @Bean
    public Computer computer() {
        Computer computer = new Computer();
        computer.setId(1);
        computer.setType("筆記本");
        computer.setName("戴爾筆記本");
        return computer;
    }
}

注入時(shí):

    @Resource
    private Computer dell;

當(dāng)配置類中有多個(gè)該類型的Bean時(shí),名字不能相同,并且注入時(shí)也要按照Bean的名稱來注入。例如:

@Configuration
public class ComputerConfig {

    @Bean
    public Computer dell() {
        Computer computer = new Computer();
        computer.setId(1);
        computer.setType("筆記本");
        computer.setName("戴爾筆記本");
        return computer;
    }

    @Bean
    public Computer apple() {
        Computer computer = new Computer();
        computer.setId(2);
        computer.setType("筆記本");
        computer.setName("蘋果筆記本");
        return computer;
    }

    @Bean("hp")
    public Computer huipu() {
        Computer computer = new Computer();
        computer.setId(3);
        computer.setType("筆記本");
        computer.setName("惠普筆記本");
        return computer;
    }
}

注入:

    @Resource
    private Computer dell;

    @Resource
    private Computer apple;

    @Resource
    private Computer hp;
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容