Springboot introduction of decentralized configuration

Source: Internet
Author: User

Springboot default supports two format profiles:. Properties and. Yml. Where the. Properties is a property file and is the most common one;. Yml is a YAML-formatted file, YAML is a concise markup language. For example: The Spring.data.url defined in the properties file is defined in the Yaml file as follows

Spring:    data:        URL:

From the above can find the Yaml hierarchy more strong, specifically in the project to choose the kind of resource file is not a rule.

Spring Boot Configuration Simple case

First create the Application.properties file and define the NAME=YSL to create a Java class that asks name

Package Com.ysl.entity;import Org.springframework.beans.factory.annotation.value;import org.springframework.stereotype.Component; @Component Public classUser {@Value ("${name:wdd}")    PrivateString name;  PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }}

Invoking the user object in TestController

Package Com.ysl.controller;import Com.ysl.entity.user;import Org.springframework.beans.factory.annotation.autowired;import org.springframework.web.bind.annotation.*; @RestController Public classTestController {@AutowiredPrivateuser User; @RequestMapping (Value="/{name}", method =requestmethod.get) @ResponseBody PublicString Home (@PathVariable ("name") (String name) {return "Hello,"+name; }}

Start the Spring boot project, enter HTTP://LOCALHOST:8080/DDD in the browser, and display the HELLO,WDD

Analytical

1. In Springboot, the default load classpath:/,classpath:/config/,file:./,file:./config/ path under the application named property or Yaml file;

2. Parameter spring.config.location setting configuration file storage location

3. Parameter Spring.config.name Setting the configuration file storage Name

Configuration file get random number

In Springboot, the method in random is called to get a random number, as an example: Add Age=${random.int} in Application.properties, and colleagues modify the user object. Generates a random value for age.

@Value ("${age}")    privateint age ;      Public int Getage () {        return age ;    }      Public void setage (int age ) {        this. Age = Age ;    } 

You can also limit the range of random numbers when using random, as an example:

${random. int (+)}: Limit the number of generated numbers to less than 10${random. int [0,+]} : The number of the specified range
Calling placeholders in the configuration file

To modify a configuration file:

Name=yslage=${random.  int}remark is is ${age}

To modify a bean:

@Value ("$remark")    private String remark;

Can be found to be name modified to userName , called in the configuration file ${name} is the project name

Remove @value

You can see that the previous invocation of the configuration parameter in the bean is annotated @Value , which can be omitted from spring boot.

Configuration file:

Username=liaokailinage=${random.  int[0,]}remark is are ${age}user.address=china, Hangzhou

Added user.address=china,hangzhou , in order to invoke this parameter @ConfigurationProperties to use.

@Component @configurationproperties (prefix="User") Public classUser {Private@Value ("${username:lkl}") String name; Private@Value ("${age}") Integer age; Private@Value ("${remark}") String remark; PrivateString address;

The use @ConfigurationProperties needs to be specified prefix , while the attributes in the bean and the configuration parameter names are consistent.

Entity nesting configuration
@Component @configurationproperties (prefix="User") Public classUser {Private@Value ("${username:lkl}") String name; Private@Value ("${age}") Integer age; Private@Value ("${remark}") String remark; PrivateString address; PrivateAddress detailaddress;
 Public class Address {private  String country; Private String Province; Private String City;

Configuration file:

Username=liaokailinage=${random.  int[0,]}remark is are ${age}user.address= China, Hangzhouuser.detailAddress.country=chinauser.detailAddress.province=  Zhejianguser.detailAddress.city=hangzhou

This nesting relationship is more hierarchical if it is presented through a YAML file.

User:    detailaddress:        country:china        Province:zhejiang        City:hangzhou
Configuration Collection

A person may have multiple contact addresses, then the address is a collection

@Component @configurationproperties (prefix="User") Public classUser {Private@Value ("${username:lkl}") String name; Private@Value ("${age}") Integer age; Private@Value ("${remark}") String remark; PrivateString address; PrivateAddress detailaddress; PrivateList<address> alladdress =NewArraylist<address> ();

Configuration file:

user.alladdress[0].country=chinauser.alladdress[0].province=  zhejianguser.alladdress[0].city=hangzhouuser.alladdress[1].country=  chinauser.alladdress[1].province=anhuiuser.alladdress[1].city=anqing
Multiple configuration files

Spring Boot sets a multi-profile file as simple as using annotations on a bean to @Profile("development") invoke application-development.properties|yml a file, or to invoke SpringApplication a etAdditionalProfiles() method in.

You can also specify parameters at startup spring.profiles.active .

  

Springboot introduction of decentralized configuration

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.