把一些可能会经常变动的东西写在配置文件中,可以增加程序的灵活性,避免多次改版发版。
在sping boot中除了自带的默认配置文件application.properties之外,我们还可以在resource下自定义配置文件,比方我们可以在resource下新加custom/my.properties文件,内容如下,虽然都是String格式,但通过一些处理,既可以返回数组,也可以返回Map:
kafka.producer.name=root kafka.producer.age=23
table.column.qualifier=name,age,nick_name,my_car
business.map=car:选车,service:服务,community:社区,my:我的,headline:头条
同时新建一个配置类MyConfig,内容如下:
package com.bitauto.Configuration; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.context.annotation.PropertySources; import java.util.HashMap; import java.util.Map; /** * Created by wangbin10 on 2018/5/4. */ @PropertySources({ @PropertySource("classpath:custom/my.properties"), @PropertySource(value = "${my.properties}", ignoreResourceNotFound = true)}) @Configuration public class MyConfig { @Value("${kafka.producer.name}") private String name; @Value("${kafka.producer.age}") private int age; @Value("${table.column.qualifier}") private String qualifier; @Value("${business.map}") private String businessMap; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String[] getQualifier() { return qualifier.split(","); } public void setQualifier(String qualifier) { this.qualifier = qualifier; } public Map getBusinessMap() { String[] strings = businessMap.split(","); Map<String,String> map=new HashMap(); for (String string : strings) { String[] split = string.split(":"); map.put(split[0],split[1]); } return map; } public void setBusinessMap(String businessMap) { this.businessMap = businessMap; } }
在测试文件中将MyConfig注入,即可得到配置文件中的信息。
@RunWith(SpringRunner.class) @SpringBootTest public class HbnApplicationTests { @Autowired private MyConfig myConfig; @Test public void test09(){ String name=myConfig.getName(); int age = myConfig.getAge(); System.out.println("name="+name+"age="+age); } }