springboot~Read custom configuration items

Our springboot project has its own default configuration file, which is generally composed of application.yml and bootstrap.yml. The former is the configuration of the module, the latter is the configuration of the microservice, and the background is loaded by the framework before the former.

Sometimes we need to define the configuration ourselves, it may not be a simple string, it may be an object, and the object has specific configuration sections, it is also a part of application.yml, you can add your own code, of course, you can also create a new one Brand new file.

For example, if there is a configuration consisting of name and version, we can define it under the project element in application.yml, where the project is called the prefix, which we use to decorate it when defining the configuration entity.

package test.lind.javaLindDay.utilDemo;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@ConfigurationProperties(prefix = "project")
@PropertySource(value = "classpath:config.yml")
public class MyConfig {
  private String version;
  private String name;

  public String getVersion() {
    return version;

  public void setVersion(String version) {
    this.version = version;

  public String getName() {
    return name;

  public void setName(String name) {
    this.name = name;

And the annotation @component indicates that it can be injected using @Autowired! If the configuration is only a string item, we can also use @Value to inject, the following code shows two

way of injection.

public class HomeController {
  MyConfig config;

  String app;

  public String Index() {
    return "HOME=" + config.getName() + "app=" + app;

Thanks for reading!


Guess you like