欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

spring boot 注入 property的三種方式(推薦)

 更新時間:2017年07月13日 17:16:51   投稿:mrr  
這篇文章主要介紹了spring boot 注入 property的三種方式,需要的朋友可以參考下

以前使用spring的使用要注入property要配置PropertyPlaceholder的bean對象。在springboot除  了這種方式以外還可以通過制定 配置ConfigurationProperties直接把property文件的 屬性映射到 當前類里面。

@ConfigurationProperties(prefix = "mypro", merge = true, locations = { "classpath:my.properties" })

ConfigurationProperties prefix 屬性指示property文件中屬性的前綴是什么。我這里寫的是mypro。

因此property文件的屬性必須mypro.x.y=z的形式;

     配置好ConfigurationProperties 之后就可以把property文件的屬性映射到當前類了。

mypro.a:1
mypro.b:2
abc.d:123

property 文件里面mypro前綴的有a 和b兩個。因此我在當前類就可以新建這兩個屬性。

 private int a;
 private int b;

這些需要映射的屬性一定要加上getter 和setter。因為spring是通過反射調用方法來修改屬性值的

        以前使用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標注的類,用@Bean標注要配置的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的三種方式,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!

相關文章

最新評論