Reading configuration file of SpringBoot

Let's take a look at how Spring can help us read the configuration information from the configuration file.

application.yml The contents are as follows:

wuhan2020: 2020 A novel coronavirus outbreak in Wuhan in early 2008 was a serious epidemic. However, I believe everything will be over. Come on, Wuhan! Go China!

my-profile:
  name: Guide Brother
  email: koushuangbwcx@163.com

library:
  location: Hubei, Wuhan, China
  books:
    - name: Basic law of genius
      description: Lin Chaoxi, 22, learned that Pei Zhi, the campus God who had been secretly in love for many years, was about to go abroad for further education on the day when her father diagnosed Alzheimer's disease. The school that the other side admitted was the one that her father gave up for her.
    - name: The order of time
      description: Why do we remember the past, not the future? What does time "pass" mean? Are we in time, or is time in us? Carlo·Using poetic words, Rowe invites us to think about the essence of time, an ancient problem.
    - name: Great me
      description: How to form a new habit? How to make the mind more mature? How to have a high quality relationship? How to get out of the difficult time of life?

1. Read simple configuration information through @ value

Use @ Value("${property}") to read simpler configuration information:

@Value("${wuhan2020}")
String wuhan2020;

Note that @ value is not recommended. Spring recommends the following ways to read configuration information.

2. Read and bind with bean through @ ConfigurationProperties

The LibraryProperties class is annotated with @ Component, which can be injected into the class just like ordinary bean s.

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@ConfigurationProperties(prefix = "library")
@Setter
@Getter
@ToString
class LibraryProperties {
    private String location;
    private List<Book> books;

    @Setter
    @Getter
    @ToString
    static class Book {
        String name;
        String description;
    }
}

At this time, you can inject it into the class just like you use ordinary bean s:

package cn.javaguide.readconfigproperties;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author shuang.kou
 */
@SpringBootApplication
public class ReadConfigPropertiesApplication implements InitializingBean {

    private final LibraryProperties library;

    public ReadConfigPropertiesApplication(LibraryProperties library) {
        this.library = library;
    }

    public static void main(String[] args) {
        SpringApplication.run(ReadConfigPropertiesApplication.class, args);
    }

    @Override
    public void afterPropertiesSet() {
        System.out.println(library.getLocation());
        System.out.println(library.getBooks());    }
}

Console output:

Hubei, Wuhan, China
 [ LibraryProperties.Book(name = genius basic law, description........]

3. Read and verify through @ ConfigurationProperties

We will application.yml Change it to the following, and it is obvious that this is not a correct email format:

my-profile:
  name: Guide Brother
  email: koushuangbwcx@

The ProfileProperties class is not annotated with @ Component. We use @ EnableConfigurationProperties to register our configuration bean s where we want to use ProfileProperties:

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;

/**
* @author shuang.kou
*/
@Getter
@Setter
@ToString
@ConfigurationProperties("my-profile")
@Validated
public class ProfileProperties {
   @NotEmpty
   private String name;

   @Email
   @NotEmpty
   private String email;

   //Use the default value if it is not read in the configuration file
   private Boolean handsome = Boolean.TRUE;

}

Specific use:

package cn.javaguide.readconfigproperties;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

/**
 * @author shuang.kou
 */
@SpringBootApplication
@EnableConfigurationProperties(ProfileProperties.class)
public class ReadConfigPropertiesApplication implements InitializingBean {
    private final ProfileProperties profileProperties;

    public ReadConfigPropertiesApplication(ProfileProperties profileProperties) {
        this.profileProperties = profileProperties;
    }

    public static void main(String[] args) {
        SpringApplication.run(ReadConfigPropertiesApplication.class, args);
    }

    @Override
    public void afterPropertiesSet() {
        System.out.println(profileProperties.toString());
    }
}

Because of the incorrect format of our mailbox, an error is reported when the program is running, which can not run at all, ensuring the security of data types:

Binding to target org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'my-profile' to cn.javaguide.readconfigproperties.ProfileProperties failed:

    Property: my-profile.email
    Value: koushuangbwcx@
    Origin: class path resource [application.yml]:5:10
    Reason: must be a well-formed email address

After we change the mailbox test to correct and then run it, the console can successfully print out the read information:

ProfileProperties(name=Guide Brother, email=koushuangbwcx@163.com, handsome=true)

4.@PropertySource reads the specified properties file

import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@PropertySource("classpath:website.properties")
@Getter
@Setter
class WebSite {
    @Value("${url}")
    private String url;
}

use:

@Autowired
private WebSite webSite;

System.out.println(webSite.getUrl());//https://javaguide.cn/

 

Tags: Lombok Spring Java

Posted on Thu, 18 Jun 2020 03:32:17 -0400 by jl9148