Spring Boot configuration file

Source: Internet
Author: User

Configuration file

Springboot use a global profile, the configuration file name is fixed;

? application.properties? application.yml

The role of the configuration file: Modify the default value of the Springboot auto-configuration;

Springboot at the bottom of the automatic configuration for us;

Yaml (Yaml Ain ' t Markup Language) Yaml a Markup Language: is a markup language YAML isn' t Markup Language: not a markup language; Markup Language:

The previous configuration file, mostly using the Xxxx.xml file; YAML: Data-centric, more suitable for configuration files than JSON, XML, etc.

YAML: configuration Example

server:port:8081

Xml:

< Server >    < Port >8081</port></server>

2. YAML syntax

1, basic syntax K: (space) V: Indicates a pair of key -value pairs (spaces must have);

Control the hierarchical relationship with the indentation of a space; as long as the left-aligned column of data is the same level, the attributes and values are also case sensitive ;

Server:    port:8081    Path:/hello

2, the value of the wording

literal: normal value (number, String, Boolean)

k:v: literally directly to write;

Strings are not added by default to single or double quotation marks;

"": double quotation marks ; The special characters inside the string are not escaped;

Special characters will be the meaning of their own name: "Zhangsan \ Lisi": output-"; Zhangsan line Lisi":

single quotation marks ; special characters are escaped, and special characters end up just a normal string data name: ' Zhangsan \ Lisi ': output; Zhangsan \ n Lisi

Objects, Map (properties and values) (key-value pairs):

K:V: The next line to write the relationship of the object's properties and values; Notice whether the object is indented or k:v

Friends:    Lastname:zhangsan    age:20

In-line notation:

Friends: {lastname:zhangsan,age:18}

Array (List, Set): represents an element in an array with a-value

Pets:    ‐cat    ‐dog    ‐pig

In-line notation

Pets: [Cat,dog,pig]

3. configuration file Value Injection

Configuration file

Person:    Lastname:hello    age:18    boss:false    BIRTH:2017/12/12    maps: {k1:v1,k2:12}    lists:        ‐lisi        ‐zhaoliu dog    :    name: Puppy    age:12

JavaBean:/* * Map the value of each property configured in the configuration file to this component

* @ConfigurationProperties: tell Springboot to bind all the properties in this class and the configuration in the configuration file;* prefix = "person" : Which of the following properties in the configuration file is one by one mapped *
* The automatic injection profile function that you want to use with Springboot must be used with two annotations * @Component Only This component is a component in a container to provide @ConfigurationProperties function; **/ @Component@ConfigurationProperties (prefix = "Person") Public classPerson {PrivateString LastName; PrivateInteger age; PrivateBoolean boss; PrivateDate Birth; PrivateMap<string,object>maps; PrivateList<object>lists; Privatedog Dog;//Getter Setter

We can import the configuration file processor, and we'll be prompted to write the configuration later.

<!‐‐ Import Profile processor, configuration file binding will be prompted ‐‐><Dependency>    <groupId>Org.springframework.boot</groupId>        <Artifactid>Spring‐boot‐configuration‐processor</Artifactid>    <Optional>True</Optional></Dependency>    

1, the Properties configuration file in idea default utf-8 may be garbled

2. @Value get value and @configurationproperties get value comparison

  @ConfigurationPr Operties @Value
features bulk injection properties in profile one All specify
loosely bound (loose syntax) Support (Profile write (Person.last-name and LastName)) does not support
spel does not support support @value ("#{11 * 2}")
JSR303 (@Vaildated data check) support (such as @email verify Email format import @vaildated annotations) does not support
Complex Type Encapsulation Support (acquisition of the map type list type data) not supported

(@Value syntax for getting values from a configuration file @Value ("${person.boos}"))

Configuration files can be obtained by both yml and properties ;

Tips for @Value and @ConfidurationProperties use:

If we just need to get a value from a configuration file in a business logic, use @value;

If we specifically write a JavaBean to map the configuration file, we use the @configurationproperties directly;

3. configuration file injection Value data check

@Component @configurationproperties (prefix= "Person")@Validated  Public classPerson {//@Value ("Huanghuanghui")    PrivateString name; PrivateInteger age; @Email     PrivateString Email; @Value ("${person.boos}")    PrivateBoolean Boos; PrivateList<object>lists; PrivateMap<string,object>maps; PrivateDate Brith;//Getter and Setter

4, @PropertySource & @ImportResource & @Bean

@PropertySource: Load the specified configuration file; In actual development, it is not possible to write all the configuration files in the Springboot configuration global configuration file.

It's a reasonable way to create a profile to inject yourself.

/** * Map the value of each property configured in the configuration file to this component * @ConfigurationProperties: Tells Springboot to bind all the properties in this class and the configuration in the configuration file; * prefix = "person" : Which of the following properties in the configuration file is one by one mapped * * Only this component is a component in the container to provide the @configurationproperties function of the container; * @ConfigurationProperties (prefix = " Person ") Gets the value from the global configuration file by default; * */= {" classpath:person.properties "=" person ") // @Validated

 Public classPerson {/*** <bean class= "person" >* <property name= "lastName" value= "literal/${key} Get values from environment variables, configuration files/#{spel}" ></ property>* <bean/>*///LastName must be a mailbox format//@Email//@Value ("${person.last‐name}")PrivateString LastName;//@Value ("#{11*2}")PrivateInteger age;//@Value ("true")PrivateBoolean boss;

@ImportResource: Import the Spring configuration file and let the contents of the configuration file take effect; Spring boot does not have a spring configuration file,

The configuration files we write ourselves are not automatically recognized; For spring's configuration file to take effect, the load must be labeled @ImportResource on a configuration class

@ImportResource (locations = {"Classpath:beans.xml"}) Import the spring configuration file for it to take effect

Do not write the spring configuration file: The configuration file cannot be identified by the Spring profile:

<?XML version= "1.0" encoding= "Utf‐8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/xmlschema‐instance"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring‐beans.xsd" >      <BeanID= "HelloService"class= "Com.atguigu.springboot.service.HelloService"></Bean></Beans>

/**      * Get the Spring IOC container to test if the container contains the HelloService component      */    @Autowired    ApplicationContext IOC;    @Test    publicvoid  Testhelloservice () {        boolean HelloService = Ioc.containsbean ("HelloService");        System.out.println (HelloService);//Output False    }

Springboot recommended ways to add components to a container; full annotation is recommended

You can define a configuration class as the primary configuration class, but this is not recommended :

@ImportResource (locations = "Classpath:beans.xml") @SpringBootApplicationpublicclass springbootyamlapplication {    publicstaticvoid  main (string[] args) {        Springapplication.run (springbootyamlapplication. class , args);}    }

The recommended methods are:

1, create Config folder, the left and right configuration classes are all placed under the file

2. Configuration class @configuration->spring configuration file

3. Add components to the container using @bean

/*** @Configuration: Indicates that the current class is a configuration class, which is equivalent to our previous spring configuration file * * We used to add components in the configuration file using the <bean></bean> tag * We use @Bean annotations in the configuration file*/@Configuration Public classMyappconfig {/*** The function is to add the return value of the method to the container * The default ID of this component is the method name of this method *@return     */@Bean PublicHelloService HelloService () {System.out.println ("Start adding components to the container ... "); return NewHelloService (); }}

Test:

@Autowired
ApplicationContext IOC;
@Test      Public void Testhelloservice () {        boolean helloservice = Ioc.containsbean ("HelloService");        System.out.println (HelloService);    }

Output:

Spring Boot configuration file

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.