在上一篇文章中,我們從源碼角度分析了SpringBoot解析yml配置文件的全流程,那么我們今天就來點(diǎn)實(shí)戰(zhàn),總結(jié)一下除了爛大街的@Value和@ConfigurationProperties外,還能夠通過哪些方式,來讀取yml配置文件的內(nèi)容。 1、Environment 在Spring中有一個(gè)類Environment,它可以被認(rèn)為是當(dāng)前應(yīng)用程序正在運(yùn)行的環(huán)境,它繼承了PropertyResolver接口,因此可以作為一個(gè)屬性解析器使用。先創(chuàng)建一個(gè)yml文件,屬性如下:person: name: hydra gender: male age: 18 使用起來也非常簡單,直接使用@Autowired就可以注入到要使用的類中,然后調(diào)用它的getProperty()方法就可以根據(jù)屬性名稱取出對應(yīng)的值了。@RestController public class EnvironmentController { @Autowired private Environment environment; @GetMapping("envTest") private void getEnv(){ System.out.println(environment.getProperty("person.name")); System.out.println(environment.getProperty("person.gender")); Integer autoClose = environment .getProperty("person.age", Integer.class); System.out.println(autoClose); String defaultValue = environment .getProperty("person.other", String.class, "defaultValue"); System.out.println(defaultValue); } } 在上面的例子中可以看到,除了簡單的獲取外,Environment提供的方法還可以對取出的屬性值進(jìn)行類型轉(zhuǎn)換、以及默認(rèn)值的設(shè)置,調(diào)用一下上面的接口,打印結(jié)果如下:hydra male 18 defaultValue 除了獲取屬性外,還可以用來判斷激活的配置文件,我們先在application.yml中激活pro文件:spring: profiles: active: pro 可以通過acceptsProfiles方法來檢測某一個(gè)配置文件是否被激活加載,或者通過getActiveProfiles方法拿到所有被激活的配置文件。測試接口:@GetMapping("getActiveEnv") private void getActiveEnv(){ System.out.println(environment.acceptsProfiles("pro")); System.out.println(environment.acceptsProfiles("dev")); String[] activeProfiles = environment.getActiveProfiles(); for (String activeProfile : activeProfiles) { System.out.println(activeProfile); } } 打印結(jié)果:true false pro 2、YamlPropertiesFactoryBean 在Spring中還可以使用YamlPropertiesFactoryBean來讀取自定義配置的yml文件,而不用再被拘束于application.yml及其激活的其他配置文件。 在使用過程中,只需要通過setResources()方法設(shè)置自定義yml配置文件的存儲路徑,再通過getObject()方法獲取Properties對象,后續(xù)就可以通過它獲取具體的屬性,下面看一個(gè)例子:@GetMapping("fcTest") public void ymlProFctest(){ YamlPropertiesFactoryBean yamlProFb = new YamlPropertiesFactoryBean(); yamlProFb.setResources(new ClassPathResource("application2.yml")); Properties properties = yamlProFb.getObject(); System.out.println(properties.get("person2.name")); System.out.println(properties.get("person2.gender")); System.out.println(properties.toString()); } 查看運(yùn)行結(jié)果,可以讀取指定的application2.yml的內(nèi)容:susan female {person2.age=18, person2.gender=female, person2.name=susan} 但是這樣的使用中有一個(gè)問題,那就是只有在這個(gè)接口的請求中能夠取到這個(gè)屬性的值,如果再寫一個(gè)接口,不使用YamlPropertiesFactoryBean讀取配置文件,即使之前的方法已經(jīng)讀取過這個(gè)yml文件一次了,第二個(gè)接口取到的仍然還是空值。來對這個(gè)過程進(jìn)行一下測試:@Value("${person2.name:null}") private String name; @Value("${person2.gender:null}") private String gender; @GetMapping("fcTest2") public void ymlProFctest2(){ System.out.println(name); System.out.println(gender); } 先調(diào)用一次fcTest接口,再調(diào)用fcTest2接口時(shí)會打印null值:null null 想要解決這個(gè)問題也很簡單,可以配合PropertySourcesPlaceholderConfigurer使用,它實(shí)現(xiàn)了BeanFactoryPostProcessor接口,也就是一個(gè)bean工廠后置處理器的實(shí)現(xiàn),可以將配置文件的屬性值加載到一個(gè)Properties文件中。使用方法如下:@Configuration public class PropertyConfig { @Bean public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() { PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer(); YamlPropertiesFactoryBean yamlProFb = new YamlPropertiesFactoryBean(); yamlProFb.setResources(new ClassPathResource("application2.yml")); configurer.setProperties(yamlProFb.getObject()); return configurer; } } 再次調(diào)用之前的接口,結(jié)果如下,可以正常的取到application2.yml中的屬性:susan female 除了使用YamlPropertiesFactoryBean將yml解析成Properties外,其實(shí)我們還可以使用YamlMapFactoryBean解析yml成為Map,使用方法非常類似:@GetMapping("fcMapTest") public void ymlMapFctest(){ YamlMapFactoryBean yamlMapFb = new YamlMapFactoryBean(); yamlMapFb.setResources(new ClassPathResource("application2.yml")); Map map = yamlMapFb.getObject(); System.out.println(map); } 打印結(jié)果:{person2={name=susan, gender=female, age=18}} 3、監(jiān)聽事件 在上篇介紹原理的文章中,我們知道SpringBoot是通過監(jiān)聽事件的方式來加載和解析的yml文件,那么我們也可以仿照這個(gè)模式,來加載自定義的配置文件。 首先,定義一個(gè)類實(shí)現(xiàn)ApplicationListener接口,監(jiān)聽的事件類型為ApplicationEnvironmentPreparedEvent,并在構(gòu)造方法中傳入要解析的yml文件名:public class YmlListener implements ApplicationListener { private String ymlFilePath; public YmlListener(String ymlFilePath){ this.ymlFilePath = ymlFilePath; } //... } 自定義的監(jiān)聽器中需要實(shí)現(xiàn)接口的onApplicationEvent()方法,當(dāng)監(jiān)聽到ApplicationEnvironmentPreparedEvent事件時(shí)會被觸發(fā):@Override public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { ConfigurableEnvironment environment = event.getEnvironment(); ResourceLoader loader = new DefaultResourceLoader(); YamlPropertySourceLoader ymlLoader = new YamlPropertySourceLoader(); try { List sourceList = ymlLoader .load(ymlFilePath, loader.getResource(ymlFilePath)); for (PropertySource propertySource : sourceList) { environment.getPropertySources().addLast(propertySource); } } catch (IOException e) { e.printStackTrace(); } } 上面的代碼中,主要實(shí)現(xiàn)了: 獲取當(dāng)前環(huán)境Environment,當(dāng)ApplicationEnvironmentPreparedEvent事件被觸發(fā)時(shí),已經(jīng)完成了Environment的裝載,并且能夠通過event事件獲取 通過YamlPropertySourceLoader加載、解析配置文件 將解析完成后的OriginTrackedMapPropertySource添加到Environment中 修改啟動類,在啟動類中加入這個(gè)監(jiān)聽器:public static void main(String[] args) { SpringApplication application = new SpringApplication(MyApplication.class); application.addListeners(new YmlListener("classpath:/application2.yml")); application.run(args); } 在向environment中添加propertySource前加一個(gè)斷點(diǎn),查看環(huán)境的變化: ![]() 執(zhí)行完成后,可以看到配置文件源已經(jīng)被添加到了環(huán)境中: ![]() 啟動完成后再調(diào)用一下接口,查看結(jié)果:susan female 能夠正確的取到配置文件中的值,說明自定義的監(jiān)聽器已經(jīng)生效。 4、SnakeYml 前面介紹的幾種方式,在Spring環(huán)境下無需引入其他依賴就可以完成的,接下來要介紹的SnakeYml在使用前需要引入依賴,但是同時(shí)也可以脫離Spring環(huán)境單獨(dú)使用。先引入依賴坐標(biāo): org.yaml snakeyaml 1.23 準(zhǔn)備一個(gè)yml配置文件:person1: name: hydra gender: male person2: name: susan gender: female 在使用SnakeYml解析yml時(shí),最常使用的就是load、loadlAll、loadAs方法,這三個(gè)方法可以加載yml文件或字符串,最后返回解析后的對象。我們先從基礎(chǔ)的load方法開始演示:public void test1(){ Yaml yaml=new Yaml(); Map map = yaml.load(getClass().getClassLoader() .getResourceAsStream("snake1.yml")); System.out.println(map); } 運(yùn)行上面的代碼,打印Map中的內(nèi)容:{person1={name=hydra, gender=male}, person2={name=susan, gender=female}} 接下來看一下loadAll方法,它可以用來加載yml中使用---連接符連接的多個(gè)文檔,將上面的yml文件進(jìn)行修改:person1: name: hydra gender: male --- person2: name: susan gender: female 在添加了連接符后,嘗試再使用load方法進(jìn)行解析,報(bào)錯(cuò)如下顯示發(fā)現(xiàn)了另一段yml文檔從而無法正常解析: ![]() 這時(shí)候修改上面的代碼,使用loadAll方法:public void test2(){ Yaml yaml=new Yaml(); Iterable objects = yaml.loadAll(getClass().getClassLoader() .getResourceAsStream("snake2.yml")); for (Object object : objects) { System.out.println(object); } } 執(zhí)行結(jié)果如下:{person1={name=hydra, gender=male}} {person2={name=susan, gender=female}} 可以看到,loadAll方法返回的是一個(gè)對象的迭代,里面的每個(gè)對象對應(yīng)yml中的一段文檔,修改后的yml文件就被解析成了兩個(gè)獨(dú)立的Map。 接下來再來看一下loadAs方法,它可以在yml解析過程中指定類型,直接封裝成一個(gè)對象。我們直接復(fù)用上面的snake1.yml,在解析前先創(chuàng)建兩個(gè)實(shí)體類對象用于接收:@Data public class Person { SinglePerson person1; SinglePerson person2; } @Data public class SinglePerson { String name; String gender; } 下面使用loadAs方法加載yml,注意方法的第二個(gè)參數(shù),就是用于封裝yml的實(shí)體類型。public void test3(){ Yaml yaml=new Yaml(); Person person = yaml.loadAs(getClass().getClassLoader(). getResourceAsStream("snake1.yml"), Person.class); System.out.println(person.toString()); } 查看執(zhí)行結(jié)果:Person(person1=SinglePerson(name=hydra, gender=male), person2=SinglePerson(name=susan, gender=female)) 實(shí)際上,如果想要將yml封裝成實(shí)體對象,也可以使用另一種方法。在創(chuàng)建Yaml對象的時(shí)候,傳入一個(gè)指定實(shí)體類的構(gòu)造器對象,然后直接調(diào)用load方法就可以實(shí)現(xiàn):public void test4(){ Yaml yaml=new Yaml(new Constructor(Person.class)); Person person = yaml.load(getClass().getClassLoader(). getResourceAsStream("snake1.yml")); System.out.println(person.toString()); } 執(zhí)行結(jié)果與上面相同:Person(person1=SinglePerson(name=hydra, gender=male), person2=SinglePerson(name=susan, gender=female)) SnakeYml其實(shí)實(shí)現(xiàn)了非常多的功能,這里就不一一列舉了,有興趣的小伙伴可以自己查看一下文檔。如果你看了上一篇的文章后跟著翻閱了一下源碼,那么你會發(fā)現(xiàn),其實(shí)在SpringBoot的底層,也是借助了SnakeYml來進(jìn)行的yml的解析操作。 5、jackson-dataformat-yaml 相比大家平常用jackson比較多的場景是用它來處理json,其實(shí)它也可以用來處理yml,使用前需要引入依賴: com.fasterxml.jackson.dataformat jackson-dataformat-yaml 2.12.3 使用jackson讀取yml也非常簡單,這里用到了常用的ObjectMapper,在創(chuàng)建ObjectMapper對象時(shí)指定使用YAML工廠,之后就可以簡單的將yml映射到實(shí)體:public void read() throws IOException { ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory()); InputStream input = new FileInputStream("F:\\Work\\yml\\src\\main\\resources\\snake1.yml"); Person person = objectMapper.readValue(input, Person.class); System.out.println(person.toString()); } 運(yùn)行結(jié)果:Person(person1=SinglePerson(name=hydra, gender=male), person2=SinglePerson(name=susan, gender=female)) 如果想要生成yml文件的話,可以調(diào)用ObjectMapper的writeValue方法實(shí)現(xiàn):public void write() throws IOException { Map map=new HashMap<>(); SinglePerson person1 = new SinglePerson("Trunks", "male"); SinglePerson person2 = new SinglePerson("Goten", "male"); Person person=new Person(person1,person2); map.put("person",person); ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory()); objectMapper .writeValue(new File("F:\\Work\\yml\\src\\main\\resources\\jackson-gen.yml"),map); } 查看生成的yml文件,可以看到j(luò)ackson對字符串類型嚴(yán)格的添加了引號,還在文檔的開頭添加了yml的鏈接符。至于其他jackson讀寫yml的復(fù)雜功能,大家可以在工作中自己去探索使用。 ![]() 總結(jié) 本文介紹了5種讀取yml配置文件的方式,前3種依賴于Spring環(huán)境,而SnakeYml和Jackson則可以脫離環(huán)境獨(dú)立使用,可以說它們是對@Value和@ConfigurationProperties注解使用的補(bǔ)充。這幾種方法的使用場景不同,也各有各的有優(yōu)點(diǎn),各自具備一些特殊的用法,而我們在工作中更多情況下,要根據(jù)具體的用途進(jìn)行一種方案的選取或多種的搭配使用。 微信8.0將好友放開到了一萬,小伙伴可以加我大號了,先到先得,再滿就真沒了 |
|