Springboot-guide, github.com/Snailclimb/, springBoot-Guide, springBoot-Guide, github.com/Snailclimb/… . Make it easier to learn Spring! If you feel good, welcome to click a Star!

Most of the time, we need to put some common configuration information, such as ali cloud OSS configuration, sending SMS information configuration and so on, into the configuration file.

Let’s take a look at some of the ways That Spring provides us to read this configuration information from a configuration file.

Application. Yml contains the following contents:

wuhan2020: 2020There was a novel coronavirus outbreak in Wuhan at the beginning of the year, but I'm sure everything will pass! Come on, Wuhan! Come on China!

my-profile:
  name: The elder brother of the Guide
  email: [email protected]

library:
  location: Go Wuhan, Hubei go China
  books:
    - name: Basic Law of Genius
      description: Lin Zhaoxi, 22, was diagnosed with Alzheimer's disease when he learned that pei Zhi, the campus boy he had been in love with for years, was going abroad for further study -- the school he was admitted to was the one his father had given up for her.
    - name: Order of time
      description: Why do we remember the past, not the future? What does it mean for time to "go by"? Do we exist within time, or does time exist within us? In poetic prose, Carlo Rovelli invites us to consider this age-old conundrum: the nature of time.
    - name: Amazing Me
      description: How to form a new habit? How to let the mind become more mature? How to have quality relationships? How do you get through tough times in your life?

Copy the code

1. By@valueRead simple configuration information

Use @value (“${property}”) to read simpler configuration information:

@Value("${wuhan2020}")
String wuhan2020;
Copy the code

One thing to note@valueThis is not recommended, and Spring recommends the following ways to read configuration information.

2. By@ConfigurationPropertiesRead and bind to the bean

LibraryPropertiesWith the class@ComponentAnnotations, which can be injected into a class just like a normal bean.


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; }}Copy the code

At this point you can inject it into the class just as you would with a normal bean:

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(a) { System.out.println(library.getLocation()); System.out.println(library.getBooks()); }}Copy the code

Console output:

[LibraryProperties.Book(name= Genius Basic Law, description........]Copy the code

Through 3.@ConfigurationPropertiesRead and verify

Let’s change application.yml to the following, which clearly shows that this is not the correct email format:

my-profile:
  name: The elder brother of the Guide
  email: koushuangbwcx@
Copy the code

ProfilePropertiesClass does not add@ComponentAnnotation. We’re in we’re going to useProfilePropertiesWhere to use@EnableConfigurationPropertiesTo register our configuration bean:

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;

   // If the configuration file is not read, use the default value
   private Boolean handsome = Boolean.TRUE;

}
Copy the code

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(a) { System.out.println(profileProperties.toString()); }}Copy the code

Because the format of our mailbox is not correct, so when the program runs, the error will be reported, which can not run at all, to ensure the security of the data type:

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
Copy the code

If we change the mailbox test to correct and run it again, the console will successfully print the read message:

ProfileProperties(name=Guide哥, [email protected], handsome=true)
Copy the code

4.@PropertySourceReads 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;
}
Copy the code

Use:

@Autowired
private WebSite webSite;

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

Copy the code

5. Digression: The priority of Spring loading configuration files

Spring reads configuration files with priority, as shown above:

IO /spring-boot…

Source: github.com/Snailclimb/…

Open Source Project Recommendation

Other open source projects recommended by the authors:

  1. JavaGuide: A Java learning + Interview Guide that covers the core knowledge that most Java programmers need to master.
  2. Springboot-guide: A Spring Boot tutorial for beginners and experienced developers.
  3. Advancer-advancement: I think there are some good habits that technical people should have!
  4. Spring-security-jwt-guide: Start from Scratch! Spring Security With JWT (including permission validation) backend part of the code.

The public,