Springboot Basic Series--properties Configuration

Source: Internet
Author: User

Original works, can be reproduced, but please mark the source address: http://www.cnblogs.com/V1haoge/p/7183408.html

Most manual configurations are exempt from springboot, but for some specific situations, we need to configure them manually, Springboot provides us with a application.properties configuration file that allows us to customize the configuration to modify the default configuration to fit the specific production situation and, of course, some third-party configurations. Almost all configurations can be written to the Application.peroperties file, this file will be automatically loaded by springboot, eliminating the hassle of loading manually. But in fact, many times we will customize the configuration files, these files need us to manually load, Springboot will not automatically recognize these files, the following to carefully look at these aspects of the content.

1, the format of the configuration file

Springboot can recognize the configuration files in two formats, namely the Yml file and the properties file, We can change the application.properties file to Application.yml, all two files can be springboot automatically recognized and loaded, but if it is a custom configuration file, it is best to use the properties format file, because Springbo The function of manually loading YML format files (referred to as annotations) is not available in OT.

Application.properties configuration file to be springboot automatically loaded, need to be placed in the specified location: Src/main/resource directory, the general custom configuration file is also located under this directory.

2, the configuration file loading

Loading means reading a file into a spring container, or, more specifically, loading individual configuration items into a spring context container for ready access.

The application.properties configuration file is automatically loaded when the Springboot project is started, and its internal settings automatically override the Springboot default settings, so the configuration items are saved to the spring container.

1-Public config file: application.properties

1 donghao.name= unique hao 2 donghao.sex= man 3 donghao.age=80

Custom xxx.properties profiles are not automatically loaded by springboot and need to be manually loaded, where manual loading is generally referred to as annotation loading, here is one of our priorities today: loading annotations for custom properties files: @ Propertysource ("Classpath:xxx.properties"), this annotation is specifically used to load the properties file at the specified location, and spring does not provide annotations to load the Yml file at the specified location, so there is a previous argument.

2-Custom configuration file: Donghao.properties

1 donghao1.name= animation 2 donghao1.sex= female 3 donghao1.age=22

In fact, no matter where the properties file, when we need to use the configuration content, it is at the top of the current class to raise the note, the configuration file loaded into memory, the configuration files can be used multiple times.

3. Use of configuration items

The use of configuration items is simple, as long as the configuration items loaded into the spring container can be referenced directly using @value ("${key}"), which is typically configured at the top of the field, indicating that the value of the configuration item is assigned to the field.

Of course, it's more about binding these configuration items to a javabean and binding them once so that we can use them at any time. Here are two scenarios, one of which is to bind the configuration in application.properties with JavaBean, one to bind the configuration in the custom configuration file to JavaBean.

The first type: Applicaiton.properties Property binding JavaBean

This is relatively simple (because the Application.properties file is automatically loaded, that is, the configuration item is automatically loaded into the memory, into the spring container, without the manual load configuration), and then we add @ at the top of the class definition of the JavaBean to bind to the property Component Annotations and @configurationproperties (prefix= "key") are annotated, the former is intended for this javabean to be scanned and loaded into the spring container when the Springboot project is started. The emphasis is on the latter, which is generally not used alone, and is generally used in conjunction with the @enableconfigurationproperties (Javabean.class), but they are not used in the same location, @ Configurationproperties (prefix= "key") annotation is raised on the JavaBean class definition, which can literally be interpreted as a property configuration annotation, the more direct point is the attribute binding annotation, The official explanation is that if you want to bind or verify some of the additional attributes from the. properties file, you can raise the annotation on a @bean annotated method or on a class in a labeled @configuration class. We can fully interpret it as binding-specific annotations. Its role is to bind the value of the specified prefix's configuration item to the JavaBean field, and note that in order for the binding to succeed, the name of the field is usually the same as the last key of the configuration key, so that the entire key is bound with the field name in the case of removing the prefix.

The second type: custom-configured property bindings JavaBean

This is the same as before, except that it cannot be loaded automatically, it needs to be loaded manually, and the @propertysource annotations above JavaBean are loaded with the configuration file. One more thing is to change @component to @configuration, why do you do it?

The bottom of the @Configuration annotation is @component, but the meaning of the two is different, @Configuration annotations focus on the meaning of configuration, @Component focus on the meaning of components, of course, configuration is one of the project components, Here we are going to bind the profile properties to JavaBean, and of course more on the meaning of configuration.

After binding the configuration with JavaBean, we can get the contents of the configuration through JavaBean, and JavaBean has been loaded into the spring container by @component annotations or @configuration annotations. We can use the automatic injection method in other classes.

One thing to note here is that when we want to use this JavaBean in a class, we need to specify the type of this javabean in this class, which is also made using annotations, which is the @enableconfigurationproperties annotation described earlier. This annotation is used with @configurationproperties annotations. An official explanation: This annotation is an effective support for @configurationproperties. Beans Annotated with @configurationproperties annotations can be registered using standard methods (using @bean annotations) or, for convenience, by using @enableconfigurationproperties to specify registration. This annotation provides a convenient way to register a bean directly.

3-Binding JavaBean:Donghao.java

1  PackageCom.donghao.model;2 3 Importorg.springframework.boot.context.properties.ConfigurationProperties;4 Importorg.springframework.context.annotation.Configuration;5 ImportOrg.springframework.context.annotation.PropertySource;6 7 @Configuration8 @PropertySource ("classpath:donghao.properties") 9 @ConfigurationProperties (prefix= "Donghao1") Ten  Public classDonghao { One     PrivateString name; A     PrivateString sex; -     PrivateString age; -      PublicString GetName () { the         returnname; -     } -      Public voidsetName (String name) { -          This. Name =name; +     } -      PublicString Getsex () { +         returnsex; A     } at      Public voidsetsex (String sex) { -          This. Sex =sex; -     } -      PublicString getage () { -         returnAge ; -     } in      Public voidsetage (String age) { -          This. Age =Age ; to     } +}

4-Define controller: Donghaocontroller

1  PackageCom.donghao.controller;2 3 Importorg.springframework.beans.factory.annotation.Autowired;4 ImportOrg.springframework.beans.factory.annotation.Value;5 Importorg.springframework.boot.context.properties.EnableConfigurationProperties;6 Importorg.springframework.web.bind.annotation.RequestMapping;7 ImportOrg.springframework.web.bind.annotation.RestController;8 9 ImportCom.donghao.model.Donghao;Ten  One @RestController A@RequestMapping ("/donghao") - @EnableConfigurationProperties (Donghao.  Class)  -  Public classDonghaocontroller { the      - @Autowired - Donghao Donghao; -      +     @Value ("${donghao.name}")  -     PrivateString name; +      A     @Value ("${donghao.sex}")  at     PrivateString sex; -      -     @Value ("${donghao.age}")  -     PrivateString age; -  -      in@RequestMapping ("/hello") -      PublicString Hello () { to         return"My name is" +name+ ", I Am" +sex+ "life, this year" +age+ "years old!; +     } -      the@RequestMapping ("/ss") *      PublicString SS () { $         returnDonghao.getname () +donghao.getsex () +donghao.getage ();Panax Notoginseng     } -}

5-Define Startup entry class: Donghaoapplication.java

1  PackageCom.donghao;2 3 Importorg.springframework.boot.SpringApplication;4 Importorg.springframework.boot.autoconfigure.SpringBootApplication;5 6 @SpringBootApplication7  Public classdonghaoapplication {8 9      Public Static voidMain (string[] args) {Ten          OneSpringapplication.run (donghaoapplication.class, args); A          -     } -  the}

After starting the program, the browser accesses: Http://localhost:8080/donghao/hello and the result is:

Browser access: HTTP://LOCALHOST:8080/DONGHAO/SS

I would like to stress here that loading and using is not associated, although loading and using is not strongly correlated between loading and use, we can completely load but not be practical, so we should analyze the loading process separately from the process used, they correspond to different annotations, These annotations are not strongly related, they each have their own use, each has a role, if just load a custom configuration file, as long as a @propertysource annotation is done, the use of the annotations do not have to use, when the use of using, we can choose a variety of ways to use, When used directly, we use the @value annotation for direct assignment, which allows you to assign values to the specified fields directly from the property configuration that is loaded into the spring container, or you can use the Bind JavaBean method.

It is also important to note that Do not configure different values for the same configuration items in the public Profile application.properties and custom profile xxx.properties, because the public profile has the highest priority, overwriting the contents of the custom configuration file, and you can understand that a configuration in the public configuration file is loaded into the spring container at startup, and then a configuration item with the same name is loaded in another custom profile, with different values, but the system checks the precedence of the two, who stays high and who is low, and the value in the last custom configuration file is invalid.

Springboot Basic Series--properties 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.