@ConfigurationProperties的使用

1. 注解在類(lèi)上時(shí)

當(dāng)@ConfigurationProperties注解在類(lèi)上時(shí),并且此類(lèi)同時(shí)注解@Component,如下所示

@ConfigurationProperties(prefix = "account")
@Component
public class AccountProperties {

    private String username;

    private String password;
    
    // 省略了get set方法
}

我可以直接通過(guò)@Autowired 注解在Bean直接獲取

@RestController
public class DemoController {

    @Autowired
    private AccountProperties accountProperties;

}

如果沒(méi)有注解@Component時(shí),例如

@ConfigurationProperties(prefix = "account")
public class AccountProperties {

    private String username;

    private String password;
    
    // 省略了get set方法
}

我們可以通過(guò)注解@EnableConfigurationProperties獲取,例如

@RestController
@EnableConfigurationProperties({AccountProperties.class})
public class DemoController {

    @Autowired
    private AccountProperties accountProperties;

}

2. 注解在方法上時(shí)

當(dāng)注解在方法上,需配合@Bean使用

@Configuration
public class DemoConfig {
    
    @Bean
    @ConfigurationProperties(prefix = "account")
    public AccountProperties accountProperties() {
        return new AccountProperties();
    }

}
?著作權(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),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

  • 1.1 spring IoC容器和beans的簡(jiǎn)介 Spring 框架的最核心基礎(chǔ)的功能是IoC(控制反轉(zhuǎn))容器,...
    simoscode閱讀 6,848評(píng)論 2 22
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,272評(píng)論 6 342
  • 1.1 Spring IoC容器和bean簡(jiǎn)介 本章介紹了Spring Framework實(shí)現(xiàn)的控制反轉(zhuǎn)(IoC)...
    起名真是難閱讀 2,671評(píng)論 0 8
  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,551評(píng)論 19 139
  • 人的一生有太多無(wú)法選擇,也許有人說(shuō)有情比無(wú)情好,但那只在電視劇里,現(xiàn)實(shí)也許也有,但生活早已把這玩意磨滅!隨著慢慢成...
    月下伊人飲酒醉閱讀 141評(píng)論 0 0

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