Springboot configuration file read in two ways, and the annotation used to explain

Source: Internet
Author: User

Having known spring-boot, you should know the Spring-boot core configuration file Application.properties, and of course you can customize the profile information by annotating it.

Pom file

<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactid >spring-boot-starter-web</artifactId> </dependency> <!--unit Test usage-<dependency> &L T;groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-test</artifactid > </dependency> <dependency> <groupId>junit</groupId> <artifactid>junit&l t;/artifactid> <scope>test</scope> </dependency> <dependency> <groupid>or G.springframework.boot</groupid> <artifactId>spring-boot</artifactId> <version>1.5.6.rel ease</version> </dependency> <dependency> <groupid>org.springframework.boot</groupid     > <artifactId>spring-boot-autoconfigure</artifactId> <version>1.5.6.RELEASE</version> </dependency> <depeNdency> <groupId>org.springframework.boot</groupId> &LT;ARTIFACTID&GT;SPRING-BOOT-AUTOCONFIGURE&L t;/artifactid> <version>1.5.6.RELEASE</version> </dependency> </dependencies>

Spring-boot How to read the configuration file:

I. Reading the contents of the core profile information application.properties

The core configuration file refers to the application.properties or application.yml configuration file under the resources root directory, and there are two ways to read the two configuration files, both of which are relatively simple.

The core configuration file Application.properties content is as follows:

test.msg=Hello World springboottest.name=Testtest.password= 123test

Mode one: Using @value (Common)

 PackageCn.ar.controller;ImportOrg.springframework.beans.factory.annotation.Value;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RestController;ImportJava.util.Map;/*** Created with IntelliJ idea. * User:jayden * DATE:2018/6/28 * time:9:57*/@RestController
@PropertiesSource ("Classpath:application.properties") Public classFirstcontroller {@Value ("${test.name}") PrivateString name; @Value ("${test.password}") PrivateString password; @RequestMapping (Value= "/test") PublicString Say () {returnName+ ": Application.propertoes inside Name value" + "/t" +password+ "password"; }}

Note: 1. The key name in the core configuration file is included in the @value ${}. Adding @restcontroller to the controller class means that all views in this class are displayed in JSON, similar to adding @responsebody on the view method.

[Email protected] Configuration file path settings, add annotations on the class, if you can not add the note under the default path, I am here in the default path, so it does not use this annotation.
If there are many directories, such as classpath:config/my.properties refers to the my.properties file under the Config directory in the src/main/resources directory.

3. Multiple profile references, if you take the value of the same property name in two configuration files, the value is the value in the last configuration file:

For example: @PropertySource ({"classpath:config/my.properties","Classpath:config/config.properties"})

Access: Http://localhost:8080/test: "mode one: Test:application.propertoes inside the name value/t123test password"

Mode two: Use Environment way

 PackageCn.ar.controller;Importorg.springframework.beans.factory.annotation.Autowired;ImportOrg.springframework.beans.factory.annotation.Value;Importorg.springframework.core.env.Environment;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RestController;ImportJava.util.Map;/*** Created with IntelliJ idea. * User:jayden * DATE:2018/6/28 * time:9:57*/@RestController Public classFirstcontroller {/*@Value ("${test.name}") private String name;    @Value ("${test.password}") private String password; @RequestMapping (value = "/test") public String Say () {return name+ ": Application.propertoes Name Value" + "/t" +passwo    rd+ "Password"; }*/@AutowiredPrivateEnvironment env; @RequestMapping (Value= "/test")     PublicString Say () {returnEnv.getproperty ("test.name") + "" "+env.getproperty (" Test.password "); }}

Note: This is done by relying on injection evnironment, adding @autowired annotations to the member variable created on the private environment env to complete the dependency injection, and then using Env.getproperty ("Key Name") The corresponding value can be read out.

Two. Read the custom profile information, for example: detifalmanager.properties

    1. First establish the object-to-profile mapping relationship
    2. method, the object is injected, and the Get method is called to get the property value
    3. Note: The new version of @configurationproperties does not have the Location property and uses @propertysource to specify the configuration file locations
    4. prefix= "user1" refers to a prefix in a configuration file, such as User1.name, which is the private String name when defining an object property name;
    5. When reading a collection in a configuration file, the list is used to receive the data, but the list must first be instantiated and the error will be

In order not to destroy the original ecology of the core file, but also need to have the custom configuration information exists, in general will choose the custom configuration file to put these custom information, here resources creates the configuration file in the directory Detifalmanager.properties

resources/detifalManager.propertiesThe contents are as follows:

User1.name=Admin11111111user1.password=admin123qwqwquser1.age=user1.sex= male

To create an entity class that manages the configuration:
 PackageCn.ar.controller;Importorg.springframework.boot.context.properties.ConfigurationProperties;ImportOrg.springframework.context.annotation.PropertySource;Importorg.springframework.stereotype.Component;/*** Created with IntelliJ idea. * User:jayden * DATE:2018/6/28 * time:10:24*/@Component//Add comment @component, you can use @autowired to create a Column object directly elsewhere@ConfigurationProperties (prefix = "user1")//to set a prefix for a configuration file@PropertySource ("Classpath:detifalManager.properties")//to set the path to a custom file Public classManager {PrivateString name; PrivateString password; PrivateString sex; Private intAge ;  PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicString GetPassword () {returnpassword; }     Public voidSetPassword (String password) { This. Password =password; }     PublicString Getsex () {returnsex; }     Public voidsetsex (String sex) { This. Sex =sex; }     Public intGetage () {returnAge ; }     Public voidSetage (intAge ) {         This. Age =Age ; }}

Attention:
There are two properties in the @configurationproperties comment:
Locations: Specify the location of the configuration file
Prefix: Specifies the prefix of the key name in the configuration file (I have all the key names in the configuration file as User1.)
Using @component is to allow the class to be used elsewhere, using @autowired annotations to create instances.

Create a test controller

 PackageCn.ar.controller;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RestController;/*** Created with IntelliJ idea. * User:jayden * DATE:2018/6/28 * time:10:33*/@RestController Public classSecondcontroller {@Autowired Manager manager; @RequestMapping ("/test1")     PublicString Say () {return"Name" + manager.getname () + "password" +Manager.getpassword (); }}

Note: Because annotation @component is added to the manager class, it is possible to create its instance object directly here using @autowired.

Access: Http://localhost:8080/test1: "Name admin11111111 password Admin123qwqwq"

Springboot configuration file read in two ways, and the annotation used to explain

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.