Spingboot The value injection problem of the configuration file

Source: Internet
Author: User

What we are studying here is the problem of injecting yml configuration file values:

Person :    lastName: Zhang San         2018-10-11 maps: {k1:        V1,K2:V2}    lists:      - pig      - dog    dog:      name: half       1

An entity class that defines a person:

 Packagecom.example.demo.entity;Importorg.springframework.boot.context.properties.ConfigurationProperties;Importorg.springframework.stereotype.Component;Importjava.util.Date;Importjava.util.List;ImportJava.util.Map;/*** Map the property values configured in the configuration file to the component * @ConfigurationProperties: Tell Springboot to bind all the properties in this class and the configuration in the configuration file * prefix = "person" Which of the following properties in the configuration file is one by one mapped * Only this component is a component in the container to use the functionality of the @configurationproperties provided by the container*/@Component @configurationproperties (prefix= "Person") Public classPerson {PrivateString LastName; PrivateInteger age; PrivateBoolean boss; PrivateDate Birth; PrivateMap<string,object>maps; PrivateList<object>lists; PrivateDog Dog; @Override PublicString toString () {return"person{" + "lastname=" "+ lastName +" \ "+", age= "+ Age +", boss= "+ BOS                S + ", birth=" + Birth + ", maps=" + maps + ", lists=" + Lists + ", dog=" + Dog + '} '; }

Define a dog's entity class again

 Packagecom.example.demo.entity; Public classDog {PrivateString name; PrivateInteger age; @Override PublicString toString () {return"dog{" + "name=" + name + ' \ ' + ", age=" + Age + '} '; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicInteger getage () {returnAge ; }     Public voidsetage (Integer age) { This. Age =Age ; }}
Set/get method ...

Define a test class again:

 PackageCom.example.demo;ImportCom.example.demo.entity.Person;Importorg.junit.Test;ImportOrg.junit.runner.RunWith;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.boot.test.context.SpringBootTest;ImportOrg.springframework.test.context.junit4.SpringRunner;/*** Springboot Test * can be very convenient during the test, such as code-like automatic injection and other functions of the container*/@RunWith (Springrunner.class) @SpringBootTest Public classdemoapplicationtests {@Autowired person person; @Test Public voidcontextloads () {System.out.println (person); }}

Test results:

Focus:

2. @Value get value and @configurationproperties get value comparison
@ConfigurationProperties @Value
Function Bulk injection properties in a configuration file Specify
Loosely bound (loose syntax) Support Not supported
Spel Not supported Support
JSR303 Data validation Support Not supported
Complex Type Encapsulation Support Not supported

Configuration file Yml or properties they can get the value;

If we just need to get a value from a configuration file in a business logic, use @value;

If we specifically write a JavaBean to map the configuration file, we use the @configurationproperties directly;

So we can also use @value () to assign values:

@Component Public classPerson {   //LastName must be a mailbox format@Value ("${person.last-name}")    PrivateString LastName; @Value ("#{11*2}")    PrivateInteger age; @Value ("true")    PrivateBoolean boss; PrivateDate Birth; PrivateMap<string,object>maps; PrivateList<object>lists; PrivateDog Dog;

Data validation when the profile value is injected:

@Component @configurationproperties (prefix= "Person") @Validated Public classPerson {   //LastName must be a mailbox format@Email    PrivateString LastName;    PrivateInteger age;PrivateDate Birth; PrivateMap<string,object>maps; PrivateList<object>lists; PrivateDog Dog;
private Boolean boss;
3, @PropertySource & @ImportResource & @Bean

@propertysource: Loads the specified configuration file, maps the value of each property configured in the configuration file to this component
@ConfigurationProperties: Tell Springboot to bind all the properties in this class and the associated configuration in the configuration file.
prefix = "person": Which of the following properties in the configuration file is one by one mapped only this component is a component in the container to

The @configurationproperties feature provided by the container, @ConfigurationProperties (prefix = "person") by default from the global

Gets the value in the configuration file.

@PropertySource (value = {"Classpath:person.properties")}) @Component @configurationproperties (prefix= "Person") Public classPerson {PrivateString LastName; PrivateInteger age; PrivateBoolean boss; PrivateDate Birth; PrivateMap<string,object>maps; PrivateList<object>lists; PrivateDog Dog;
}
Set/get method .....

@importresource: Import the Spring configuration file, let the contents of the configuration file take effect;

Spring boot does not have a spring configuration file, and the configuration files we write ourselves are not automatically recognized;

Want spring's configuration file to take effect, load it in; @importresource label on a configuration class

@ImportResource (locations = {"Classpath:beans.xml"}) Import the spring configuration file for it to take effect

Springboot recommended ways to add components to a container; full annotation is recommended

1. Configuration class @Configuration

2. Use @Bean to add components to the container

@Configuration  Public class myappconfig {    // adds the return value of the method to the container; The default ID of this component in the container is the method name     @Bean      public HelloService Helloservicfun () {        System.out.println ("configuration class @bean adding components to the container ...");         return New HelloService ();    }}

Spingboot The value injection problem of the configuration file

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.