How springboot read custom configuration item

We springboot project has its own default configuration file, typically by the application.yml and bootstrap.yml, the former is the configuration of the module, which is configured micro services, backstage former first frame is loaded.

Sometimes we need to define the configuration may not be simple string, it may be an object, an object, there are specific configuration section, which is also part of application.yml, you can add code to put on their own, of course, you can create the new file.

For example, there is a configuration consisting of the name and version, we can define it as the following project elements in application.yml years, project here called prefix, when it is used to modify the configuration of our entity in the definition.

 package test.lind.javaLindDay.utilDemo;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@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;
 }
}

Which comments @component representation can be used @Autowired injection! If the item configuration in just a string, we can also use @Value be injected, the following code to show two

Injection method.

@RestController
public class HomeController {
 @Autowired
 MyConfig config;
 @Value("${lind.name}")
 String app;
 @RequestMapping("/")
 public String Index() {
  return "HOME=" + config.getName() + "app=" + app;
 }
}

Guess you like

Origin blog.csdn.net/xunjiushi9717/article/details/92083403