读取配置文件参数转成对象,map集合。list集合

1.   配置文件参数转成对象

        配置文件:properties形式

soul.server.host=192.168.80.96
soul.server.port=9999

       添加一个配置类:

//方式一 使用@value 注意要使用 ${}包裹
@Configuration
@Data
public class SoulConfig {
    @Value("${soul.server.host}")
    String host;
    @Value("${soul.server.port}")
    String port;
}

//方式二使用注解@configurationProperties 
@configurationProperties("soul.server")
@Configuration
@Data
public class SoulConfig {
    String host;
    String port;
}

2.配置文件转map集合,list集合

#配置文件map表示方式之一
soul.auth.map.2.appKey=99999999999999999999999999999 soul.auth.map.2.appSecret=888888888888888888888888 soul.auth.map.3.appKey=123123123123123 soul.auth.map.3.appSecret=132123123123123

#list表示方式之一
soul.auth.list[0]=apple0
soul.auth.list[1]=apple1
soul.auth.list[2]=apple2
#list表示方式之二
soul.auth.list=apple0,apple1,apple2

添加一个配置类:

@Configuration
@ConfigurationProperties(prefix = "soul.auth")
@Data
public class SoulAppConfig {
   //map集合    // 这里的属性map对应配置文件中的map ,放在yml文件其实更加一目了然 , map就是一个Map<Integer, AppKeyAndAppSecretEntity>的一个对象 Map
<Integer, AppKeyAndAppSecretEntity> map;
//list集合
     List<String> list;
//这里是再外部通过一个叫sysId的参数来获取map集合中对应键的对象(AppKeyAndAppSecretEntity)值,将配置文件中的 2和3转成集合中的key 值对应就是对象AppKeyAndAppSecretEntity
   
 public AppKeyAndAppSecretEntity getAppKeyAndAppSecretEntity(Integer sysId){
        return map.get(sysId);
    }

}


//贴一下AppKeyAndAppSecretEntity对象 
@Data
@AllArgsConstructor
@NoArgsConstructor
public class AppKeyAndAppSecretEntity {
    String appKey;
    String appSecret;
}

测试输出结果

@Autowired
    SoulAppConfig soulAppConfig;
 @Test
    public  void http() {
Map<Integer, AppKeyAndAppSecretEntity> map = soulAppConfig.getMap();

}

 

 

posted @ 2021-11-25 10:20  少侠砍人不用刀  阅读(522)  评论(0编辑  收藏  举报