springboot configuration file

1. YAML Syntax

1. Basic Grammar

The k-space v represents a pair of key-value pairs (which must have spaces) and controls hierarchical relationships by indentation of the spaces. A left-aligned column of data represents the same hierarchy.Property and value case sensitive

1 server:
2     port: 8081
3     servlet-path: /hello
2. Rules for Values

1 Literal quantity: normal value
(2) String does not need single and double quotation marks by default
(3) Double quotation marks do not escape special characters within a string, that is, if there is a \n in the string, it will wrap
(4) Single quotation marks escape special characters, which are only a common string of data.

3. Writing of objects

For example, there is an object Person and a Dog, as follows:

public class Person {
    private String username;
    private Integer age;
    private Boolean boss;
    private Date birth;

    private Map<String,Object> maps;
    private List<Object> lists;
    private Dog dog;
  //get set toString Method
 }
 
public class Dog {
    private String name;
    private Integer age;
    //get set toString Method
}

application.yml Configuration File

person:
  username: lwb
  age: 18
  boss: true
  birth: 2019/12/8
  maps: {name: wt, age: 16}
  lists: [lwb, wt]
  dog:
    name: puppy
    age: 3

The code above is a yaml notation that configures the injected value for the Person object

4. Multiple Writing

In yaml, levels are controlled by indentation, but there is another way to write objects, map s, arrays, lists, set s, and so on.

#Object inline writing
person: {username: zhangsan,age: 20}
#Array (List, Set)
pets:
  ‐ cat
  ‐ dog
  ‐ pig
#perhaps
pets: [cat,dog,pig]

2. Examples of application.properties writing review

person.age=18
person.birth=2019/12/7
person.boss=true
person.maps.k1=wt
person.maps.k2=19
person.dog.name=puppy
person.dog.age=3
person.lists=a,b,c

3. Profile Injection

To inject values from the configuration file into a javabean object, you need to determine the import

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

The final experimental environment is:

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

To automatically inject values from the configuration file into the Person object above, you need to hand the Person over to Spring for management.So you need to add two spring annotations to the Person class:

@ConfigurationProperties(prefix = "person")
@Component
public class Person {
//Attributes like above
}

@ConfigurationProperties: Tell SpringBoot to bind all the properties in this class to the related configurations in the configuration file, prefix = "person": which of the following properties in the configuration file maps one at a time.With the above configuration, Person objects can be automatically injected where we want to get the Person object, and the initial values match the configuration in the configuration file.

@Service
public class PersonService {
    @Autowired
    private Person person;
    public void getPerson() {
        System.out.println(person);
    }
}

4. Random code in application.properties writing

As shown in the second section, using the application.properties writing method, the Chinese characters may be garbled, and the specific solutions are as follows:

And add the following configuration to the application.properties file:

spring.http.encoding.charset=utf-8
spring.http.encoding.force=true
spring.http.encoding.enabled=true

5. Use @Value to set a value

You can inject values using the spring native comment @Value

@Component
public class Person {
    @Value("${person.username}")
    private String username;
    @Value("#{11 * 2}")
    private Integer age;
    @Value("true")
    private Boolean boss;
    @Value("${person.birth}")
    private Date birth;
    private Map<String,Object> maps;
    private List<Object> lists;
    private Dog dog;
    //get set toString
 }

 

As you can see from the example above, all settings are of simple type. What happens if maps, lists, and dog s are also labeled with injection values?

@Component
public class Person {
    @Value("${person.username}")
    private String username;
    @Value("#{11 * 2}")
    private Integer age;
    @Value("true")
    private Boolean boss;
    @Value("${person.birth}")
    private Date birth;
    @Value("${person.maps}")
    private Map<String,Object> maps;
    @Value("${person.lists}")
    private List<Object> lists;
    @Value("${person.dog}")
    private Dog dog;
    // get set toString Method
}
java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:132)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:123)
    at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:190)
    at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:132)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:244)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'person': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'person.maps' in value "${person.maps}"

You can see the direct error, but there is a difference between @ConfigurationProperties and @Value, as follows:

  @ConfigurationProperties @Value
function Bulk Injection Properties in Configuration File Specify one by one
Loose Binding (Loose Syntax) (lastName --> last-name) Support I won't support it
SpEL I won't support it Support
JSR303 Data Check Support I won't support it
Complex Type Encapsulation Support I won't support it

Configuration file yml or properties both get values; if we just need to get a value in a configuration file in some business logic, use @Value; if we've specifically written a javaBean to map to a configuration file, we use @Configuration Properties directly;

Keywords: Java Spring Junit encoding

Added by stweaker on Tue, 10 Dec 2019 15:07:55 +0200