以前使用spring的使用要注入property要配置PropertyPlaceholder的bean對象。在springboot除 了這種方式以外還可以通過制定 配置ConfigurationProperties直接把property文件的 屬性映射到 當(dāng)前類里面。
成都創(chuàng)新互聯(lián)公司不只是一家網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司;我們對營銷、技術(shù)、服務(wù)都有自己獨(dú)特見解,公司采取“創(chuàng)意+綜合+營銷”一體化的方式為您提供更專業(yè)的服務(wù)!我們經(jīng)歷的每一步也許不一定是最完美的,但每一步都有值得深思的意義。我們珍視每一份信任,關(guān)注我們的成都做網(wǎng)站、成都網(wǎng)站設(shè)計質(zhì)量和服務(wù)品質(zhì),在得到用戶滿意的同時,也能得到同行業(yè)的專業(yè)認(rèn)可,能夠?yàn)樾袠I(yè)創(chuàng)新發(fā)展助力。未來將繼續(xù)專注于技術(shù)創(chuàng)新,服務(wù)升級,滿足企業(yè)一站式全網(wǎng)營銷推廣需求,讓再小的品牌網(wǎng)站建設(shè)也能產(chǎn)生價值!
@ConfigurationProperties(prefix = "mypro", merge = true, locations = { "classpath:my.properties" })
ConfigurationProperties prefix 屬性指示property文件中屬性的前綴是什么。我這里寫的是mypro。
因此property文件的屬性必須mypro.x.y=z的形式;
配置好ConfigurationProperties 之后就可以把property文件的屬性映射到當(dāng)前類了。
mypro.a:1 mypro.b:2 abc.d:123
property 文件里面mypro前綴的有a 和b兩個。因此我在當(dāng)前類就可以新建這兩個屬性。
private int a; private int b;
這些需要映射的屬性一定要加上getter 和setter。因?yàn)閟pring是通過反射調(diào)用方法來修改屬性值的
以前使用spring注入property的方式也同樣適用。以前是xml配置PropertyPlaceholder?,F(xiàn)在使用@bean 或者直接@Component配置這個類。只要把PropertyPlaceholderConfigurer添加到bean工廠,就可以使用@Value 取值了。
@Component public class MyPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer{ public MyPropertyPlaceholderConfigurer(){ this.setIgnoreResourceNotFound(true); final List<Resource> resourceLst = new ArrayList<Resource>(); resourceLst.add(new ClassPathResource("my.properties")); this.setLocations(resourceLst.toArray(new Resource[]{})); } } @Value("abc.d") private String test;
另外的一種方法跟第二種差不多的。更像以前的xml配置PropertyPlaceholder。只是現(xiàn)在的配置是用@Configuration標(biāo)注的類,用@Bean標(biāo)注要配置的bean對象;
@Configuration public class Testproperties { @Bean public PropertyPlaceholderConfigurer properties(){ final PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer(); ppc.setIgnoreResourceNotFound(true); final List<Resource> resourceLst = new ArrayList<Resource>(); resourceLst.add(new ClassPathResource("my.properties")); ppc.setLocations(resourceLst.toArray(new Resource[]{})); return ppc; } }
以上所述是小編給大家介紹的spring boot 注入 property的三種方式,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對創(chuàng)新互聯(lián)網(wǎng)站的支持!
本文標(biāo)題:springboot注入property的三種方式(推薦)
當(dāng)前網(wǎng)址:http://chinadenli.net/article42/poohhc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站設(shè)計公司、自適應(yīng)網(wǎng)站、外貿(mào)建站、營銷型網(wǎng)站建設(shè)、服務(wù)器托管、外貿(mào)網(wǎng)站建設(shè)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)