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, and the latter is the configuration of microservices. The background is loaded by the framework first than the former.
Sometimes we need to define the configuration ourselves. It may not be a simple string. It may be an object with specific configuration segments in the object. It is also part of the application.yml. You can add your own code, and of course you can also create a brand new file.
For example, there is a configuration consisting of name and version. We can define it as below the project element in application.yml. The project here is called the prefix, which we use to modify 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;@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 @Autowired injection can be used! If the configuration is just a string item, we can also use @Value to inject it. The following code shows two types of items
Injection method.
@RestControllerpublic class HomeController { @Autowired MyConfig config; @Value("${lind.name}") String app; @RequestMapping("/") public String Index() { return "HOME=" + config.getName() + "app=" + app; }}Summarize
The above is the editor’s introduction to how springboot reads custom configuration items. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support to Wulin.com website!