Play Spring Boot Custom configuration, import XML configuration and external configuration

Source: Internet
Author: User

Play Spring Boot Custom configuration, import XML configuration and external configuration
Here I'll give you a full description of how to customize the configuration in spring boot, change the spring boot default configuration, and describe the order of precedence for each configuration. Spring Boot uses a global profile application.properties,spring Boot supports configuration files using Yaml language, YAML is in the language of the data bit center, So using APPLICATION.YML as a global configuration is the same effect,If you use Yaml instead of the properties note, the colon is preceded by a space, otherwise it will not be resolved。 And in spring boot inside the configuration name supports a variety of ways, for example: Server.ssl.key-store, can be written: Server.ssl.keyStore are all possible. Detailed details are described below.
1. The reference XML file configuration in the actual project some situations need to use the XML configuration file, or you are not accustomed to Java configuration, then you can add @importresource (value = {"Path"}) on the Portal startup class or use @importr Esource (locations= {"Path"}), the same effect, multiple XML files you can use the comma "," delimited, so easy to reference the XML configuration.
2. The introduction of multiple @configuration configuration classes may not be configured in the actual project by placing all configurations in a configuration class (classes annotated with @configuration). You can then use the @import annotation reference.
3. Referencing custom properties Spring boot uses global configuration (application.properties) to provide many of the default configuration properties. In the development, most of the use of custom configuration properties, such as: Specify the path to save the upload file, definition: file.upload.stor-path=e:/test/,spring Boot provides @value annotations to get properties in property , a type-safe configuration is provided, and the properties attribute is injected into a bean by @configurationproperties, which is not recommended by the official version at least 1.4. Configurationproperties to specify the properties file location. Next, look at the example: Add the following dependencies to the Pom.xml: [HTML]View PlainCopyPrint?
  1. < Dependency >     
  2. < groupId > Org.springframework.boot </ groupId >     
  3. < Artifactid > Spring-boot-configuration-processor </ Artifactid >     
  4. < Optional > true </ Optional >     
  5. </ Dependency >    
<dependency>            <groupId>org.springframework.boot</groupId>            <artifactId> Spring-boot-configuration-processor</artifactid>            <optional>true</optional>  

The first type:(1) Create a new application.properties file under Src/main/resources and add the following code: [Plain]View PlainCopyPrint?
    1. file.upload.stor-path=e:/test/
file.upload.stor-path=e:/test/
(2) directly using @value annotation method, the specific code is as follows: [Java]View PlainCopyPrint?
  1. Package  Com.chengli.springboot.helloworld;
  2. Import  Org.springframework.beans.factory.annotation.Value;
  3. Import  org.springframework.boot.SpringApplication;
  4. Import  org.springframework.boot.autoconfigure.SpringBootApplication;
  5. Import  org.springframework.web.bind.annotation.RequestMapping;
  6. Import  Org.springframework.web.bind.annotation.RestController;
  7. @RestController   
  8. @SpringBootApplication   
  9. Public class Samplecontroller {
  10. @Value (value = "${file.upload.stor-path}")
  11. Private  String Storpath;
  12. @RequestMapping ("/")  
  13. String Home () {
  14. return  "Hello world!  File.upload.stor-path for: " + storpath;
  15. }
  16. Public  static void main (string[] args) throws Exception {
  17. Springapplication springapplication = new springapplication (samplecontroller. class  );
  18. Springapplication.run (args);
  19. }
  20. }
Package Com.chengli.springboot.helloworld;import Org.springframework.beans.factory.annotation.value;import Org.springframework.boot.springapplication;import org.springframework.boot.autoconfigure.SpringBootApplication; Import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.restcontroller;@[email protected] class Samplecontroller {    @Value ( Value = "${file.upload.stor-path}")    private String Storpath;    @RequestMapping ("/")    String Home () {        return "Hello world! File.upload.stor-path is: "+ Storpath;    }    public static void Main (string[] args) throws Exception {        springapplication springapplication = new Springapplication (Samplecontroller.class);        Springapplication.run (args);}    }
The second type:The property configuration is placed in the Application.properties file, using @configurationproperties to inject the configuration property into the bean with the following code: (1) defining the Fileuploadproperties class [Java]View PlainCopyPrint?
  1. Package  Com.chengli.springboot.helloworld;
  2. Import  org.springframework.boot.context.properties.ConfigurationProperties;
  3. Import  org.springframework.stereotype.Component;
  4. @Component   
  5. @ConfigurationProperties (prefix = "file.upload")
  6. Public class fileuploadproperties {
  7. Private  String Storpath;
  8. Public String Getstorpath () {
  9. return  Storpath;
  10. }
  11. Public void Setstorpath (String storpath) {
  12. This  . Storpath = Storpath;
  13. }
  14. }
Package Com.chengli.springboot.helloworld;import Org.springframework.boot.context.properties.configurationproperties;import Org.springframework.stereotype.component;@[email protected] (prefix = "file.upload") public class fileuploadproperties {    private String storpath;    Public String Getstorpath () {        return storpath;    }    public void Setstorpath (String storpath) {        this.storpath = Storpath;    }}
(2) The Entry start class code is as follows: [Java]View PlainCopyPrint?
  1. Package  Com.chengli.springboot.helloworld;
  2. Import  org.springframework.beans.factory.annotation.Autowired;
  3. Import  org.springframework.boot.SpringApplication;
  4. Import  org.springframework.boot.autoconfigure.SpringBootApplication;
  5. Import  org.springframework.web.bind.annotation.RequestMapping;
  6. Import  Org.springframework.web.bind.annotation.RestController;
  7. @RestController   
  8. @SpringBootApplication   
  9. Public class Samplecontroller {
  10. @Autowired   
  11. Private  fileuploadproperties fileuploadproperties;
  12. @RequestMapping ("/")  
  13. String Home () {
  14. return  "Hello world!  File.upload.stor-path for: " + Fileuploadproperties.getstorpath ();
  15. }
  16. Public  static void main (string[] args) throws Exception {
  17. Springapplication springapplication = new springapplication (samplecontroller. class  );
  18. Springapplication.run (args);
  19. }
  20. }
Package Com.chengli.springboot.helloworld;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.boot.springapplication;import org.springframework.boot.autoconfigure.SpringBootApplication; Import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.restcontroller;@[email protected] class Samplecontroller {    @Autowired    private fileuploadproperties fileuploadproperties;    @RequestMapping ("/")    String Home () {        return "Hello world! File.upload.stor-path is: "+ Fileuploadproperties.getstorpath ();    }    public static void Main (string[] args) throws Exception {        springapplication springapplication = new Springapplication (Samplecontroller.class);        Springapplication.run (args);}    }
Note: Here I use the @component annotation for fileuploadproperties, and if you do not use @component annotations, you need to add @enableconfigurationproperties annotations to the Portal startup class. Spring Boot supports the use of Spel expressions in the properties file, which can be checked (verifying that annotations use javax.validation), and so on.
For example, the following:(1) random number:Test.int.random=${random.int}(2) Array injection test.int.random[0]=${random.int} test.int.random[1]=${random.int} (3) Check@NotNull
Private String Storpath;

4. External configuration (configuration mode and priority)Spring boot allows for an external configuration, and spring boot uses a special Propertysource order to allow the values to be overwritten, overriding the order of precedence as follows: (1) devtools Global Settings Home directory (~/.  Spring-boot-devtools.properties for Active).  (2) @TestPropertySource note in test.  (3) @SpringBootTest #properties annotations in test.  (4) command-line arguments.  (5) from the Spring_application_json attribute (inline JSON embedded in an environment variable or system property).  (6) servletconfig init parameter.  (7) ServletContext init parameter.  (8) Jndi attribute java:comp/env.  (9) Java System Properties (System.getproperties ()).  (10) Operating system environment variables.  (one) Randomvaluepropertysource configured random.* property value (12) packaged in a application-{profile}.properties or application.yml configuration file other than the jar  (13) Application-{profile}.properties or APPLICATION.YML configuration files packaged within the jar  (14) Application.properties or application.yml configuration file (15) packaged in a jar outside the jar, application.properties or application.yml configuration file  () @configuration the @propertysource on the annotation class. (17) The default property (specified with Springapplication.setdefaultproperties).
A) Modify the default parameters by using the command line, for example: Start command: Java-jar *.jar--name= "Chengli" above means, modify the name value to: chenglib) by command line to set the loading properties for example: Java-jar *.jar--spring.profiles.active=devIf you don't know the profile here, you'll find it in the following article.
5.application.properties files are prioritized with high priority overrides with lower priority order as follows: (1) a/config subdirectory under the current directory (2) current directory (3)/config package (4) CLA under a classpath Sspath root directory

Interested friends can add groups to explore mutual learning:

Spring Boot QQ Exchange Group: 599546061

Play Spring Boot Custom configuration, import XML configuration and external 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.