Springboot Learning: Reading the contents of the Yml and properties files

Source: Internet
Author: User

First, implement attribute injection in Springboot:

1), add pom dependent jar package;

1 <!--Support @ConfigurationProperties Annotations -  2     <!--Https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-configuration-processor -  3     <Dependency>  4       <groupId>Org.springframework.boot</groupId>  5       <Artifactid>Spring-boot-configuration-processor</Artifactid>  6       <version>${spring-boot.version}</version>  7     </Dependency>  

2), in the YML configuration file:

1 #pojo属性注入2 mybar: #pojo中的prefix值3 Name: Zhang San4 Arrs: Zhao, Qian, Sun, Li5 NameList:6 -Name: Liu7 value: Liu Bei8 -Name: Zhang9 value: Zhang FeiTen barnamelist: One -Number of early departures A -Number of late arrivals - -Absenteeism Days - Map: the Key1: Caocao - Key2: Cao Pi -Key3: Cao Zhi

3), Pojo by the set, get method to get Ah, the value in the YML

1  PackageCn.com.venus.oa.pojo;2 3 Importjava.util.List;4 ImportJava.util.Map;5 6 Importorg.springframework.beans.factory.annotation.Autowired;7 ImportOrg.springframework.beans.factory.annotation.Value;8 Importorg.springframework.boot.context.properties.ConfigurationProperties;9 Importorg.springframework.stereotype.Component;Ten  One /** A * Methods for loading YAML configuration files - * Spring-boot updated to 1.5.2 After the Locations property is not available - * @PropertySource annotations can only load Proprties file, cannot load Yaml file the * So now put the data into the Application.yml file, Spring-boot will load when the boot -  */ - @Component -@ConfigurationProperties (prefix= "Mybar") +  Public classBar { -     PrivateString name; +  A     Privatestring[] Arrs; at  -     PrivateList<map<string,string>>NameList; -      -     PrivateList<string>barnamelist; -  -     PrivateMap<string,string>map; in  -      PublicString GetName () { to         returnname; +     } -  the     //the string type must be a setter to receive the property value; maps, collections, and arrays don't need *      Public voidsetName (String name) { $          This. Name =name;Panax Notoginseng     } -  the      Publicstring[] Getarrs () { +         returnArrs; A     } the  +      Public voidSetarrs (string[] arrs) { -          This. Arrs =Arrs; $     } $  -      PublicMap<string, string>Getmap () { -         returnmap; the     } - Wuyi      Public voidSetmap (map<string, string>map) { the          This. Map =map; -     } Wu  -      PublicList<map<string, string>>getnamelist () { About         returnNameList; $     } -  -      Public voidSetnamelist (list<map<string, string>>namelist) { -          This. NameList =NameList; A     } +  the      PublicList<string>getbarnamelist () { -         returnbarnamelist; $     } the  the      Public voidSetbarnamelist (list<string>barnamelist) { theBarnamelist =barnamelist; the     } -  in      the}

4), finally perform automatic injection in controller to complete the YML configuration property values:

1 @Autowired 2 Private  Bar Bar;

Second, the Properties configuration file:

The configuration file is loaded with the @propertysource annotation, and the note cannot load the YML profile. Using @value annotations to get parameter values in a file

 Packagecom.sun.configuration; ImportOrg.springframework.context.annotation.Bean; Importorg.springframework.context.annotation.Configuration; ImportOrg.springframework.context.annotation.PropertySource; ImportOrg.springframework.context.support.PropertySourcesPlaceholderConfigurer; /*** Load Properties configuration file, in the method can get * abc.properties file does not exist, verify Ignoreresourcenotfound property * Plus encoding = "Utf-8" property to prevent Chinese garbled, cannot be   Uppercase "UTF-8" * Created by Sun on 2017-3-30. */@Configuration @PropertySource (value= {"Classpath:/config/propconfigs.properties", "Classpath:/config/abc.properties"}, Ignoreresourcenotfound=true, encoding = "Utf-8")   Public classPropconfig {//propertysourcesplaceholderconfigurer this bean,//This bean is mainly used to solve the ${used in @value ...}      Placeholder. //If you don't use ${...}  placeholder, you can not use this bean. @Bean Public Staticpropertysourcesplaceholderconfigurer Propertysourcesplaceholderconfigurer () {return NewPropertysourcesplaceholderconfigurer (); }  }  

There are two ways to get the properties file parameter values, one to get the environment object, and the second to @value annotations

1 @Autowired2     PrivateEnvironment env; 3@Value ("${age}")  4 String name; 5   6   7@RequestMapping ("/")  8 @ResponseBody9String Home (HttpServletRequest req)throwsjsonprocessingexception, unsupportedencodingexception {TenLogger.info ("Test pass!!! ");  OneObjectmapper Objectmapper =NewObjectmapper ();  A         //Test Load Yml file -System.out.println ("Simpleprop:" +Config.getsimpleprop ());  -System.out.println ("Arrayprops:" +objectmapper.writevalueasstring (Config.getarrayprops ()));  theSystem.out.println ("LISTPROP1:" +objectmapper.writevalueasstring (CONFIG.GETLISTPROP1 ()));  -System.out.println ("LISTPROP2:" +objectmapper.writevalueasstring (CONFIG.GETLISTPROP2 ()));  -System.out.println ("Mapprops:" +objectmapper.writevalueasstring (Config.getmapprops ()));  -    +         //Test Load Properties File -System.out.println (Env.getproperty ("name"));//Sun Kai +System.out.println (Env.getproperty ("abc"));//NULL ASYSTEM.OUT.PRINTLN (name);// - at    -         return"Hello world!";  -}

Springboot Learning: Reading the contents of the Yml and properties files

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.