Springboot Project Property Configuration

Source: Internet
Author: User

We know that in the project, often need to use some configuration of things, these things may be in the test environment and production environment will have a different configuration, there may be changes later, so we can not write in the code to die, to write to the configuration. We can write these into the Application.yml file.

For example, in a microservices architecture, where a service often invokes other services to get the relevant information, it needs to configure the addresses of other services, which we can configure as follows:

server:port:8001# Configuring address URLs for multiple microservices: # The address of the Order micro Service ORDERURL:HTTP://LOCALHOST:8002 # The address of the user micro-service userurl:http://localhost:80 03 # Shopping Cart micro-service address shoppingurl:http://localhost:8004

and how do you get to these configurations in your code? We use the @Value annotations can be obtained as follows:

import org.slf4j.logger;import org.slf4j.loggerfactory;import  org.springframework.beans.factory.annotation.value;import  org.springframework.web.bind.annotation.requestmapping;import  org.springframework.web.bind.annotation.restcontroller;  @RestController @requestmapping ("/test") public  class testcontroller {     private static final logger  logger = loggerfactory.getlogger (Testcontroller.class);      @Value ("$ {Url.orderurl} ")     private String orderUrl;      @Value ("${url.userurl}")     private string userurl;     @ Value ("${url.shoppingurl}")     private String shoppingUrl;       @RequestMapping ("/config")     public string testconfig ()  {       &nbsP; logger.info ("===== Gets the order service address: {}",  orderurl);         Logger.info ("===== Gets the User Service address: {}",  userurl);         logger.info ("= = = = The shopping cart service address obtained is: {} ",  shoppingurl);        return " Success ";     }}

Very simple, after requesting the 8001 port service, you can see that the console will print out the address of three services, in the actual project is the same, and if, because of the reasons for server deployment, you need to modify the address of a service, so long as the configuration file can be modified.

There is another problem here, as business complexity increases, there may be more and more microservices in a project, so it is @Value too cumbersome and unscientific to use annotations to introduce them in code. So you can consider encapsulating a configuration class.

/** * @author Shengwu ni * @date 2018/06/11 */@Component @configurationproperties (prefix = "url") public class Microserviceu    RL {private String orderurl;    Private String Userurl;    Private String Shoppingurl; Omit get and Set methods}

Use@ConfigurationPropertiesannotations can specify a prefix, and the attribute name in the class is the name of the configuration minus the prefix. At the same time, the class above needs to add@Componentannotations, which are placed in the spring container as components. By the use of the@ConfigurationPropertiesyou need to import a dependency:

<dependency> <groupId>org.springframework.boot</groupId> <artifactId> Spring-boot-configuration-processor</artifactid> <optional>true</optional></dependency>


OK, and then write a controller to test, at this time, do not need to introduce each other, directly through the @resource annotations will just be injected into the configuration class can be used, very convenient. as follows:

@RestController @requestmapping ("/test") public class TestController {private static final Logger Logger = loggerfactory    . GetLogger (Testcontroller.class);        @Resource private Microserviceurl Microserviceurl; @RequestMapping ("/config") public String Testconfig () {logger.info ("===== Gets the order service address: {}", Microserviceurl.getord        Erurl ());        Logger.info ("===== Gets the User Service address: {}", Microserviceurl.getuserurl ());        Logger.info ("===== Gets the shopping cart service address is: {}", Microserviceurl.getshoppingurl ());    Return "Success"; }}


Focus on Small series

Two new gift packs are available

36 part-Line internet Java interview ebook

84 Java rare face question video

Address: http://yunxi.ai/java/java.html


Springboot Project Property 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.