Spring Boot Resource file property configuration
The configuration file refers to the resources root directory application.properties
or the application.yml
configuration file, read the two configuration files in two ways, are relatively simple.
Add in Pom.xml:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId> Spring-boot-configuration-processor</artifactid> <optional>true</optional></ Dependency>
first, the resource file properties are configured to read directly
/** * @author OYC * @Title: * @Description: * @date 2018/6/1321:44 * * * @RestController @requestmapping ("/resource") public CLA SS Resourcecontroller { @Value ("${com.bestoyc.opensource.name}") private String name; @Value ("${com.bestoyc.opensource.website}") private String webSite; @Value ("${com.bestoyc.opensource.language}") private String language; @RequestMapping ("/getresource1") public String GetResource1 () { return "name:" + name + "----WebSite:" + WebSite + "----Language:" + Language; }}
Note: The @Value
key name in the core configuration file is included in the ${}. adding to the controller class @RestController
means that all views in this class are displayed in JSON, similar to adding on a view method @ResponseBody
.
Second, the attribute configuration in the resource file is mapped to the entity class
You can complete the read of the property configuration by mapping the configuration property to the entity class and then injecting the entity class into the controller or service.
Property configuration file (resource.properties):
Com.bestoyc.opensource.name=bestoyccom.bestoyc.opensource.website=www.bestoyc.comcom.bestoyc.opensource.language=java
corresponding entity class (Resource.java):
/** * @author OYC * @Title: Resource file Mapping entity class * @Description: * @date 2018/6/13 21:32 */@Configuration @configurationproperties (pref IX = "Com.bestoyc.opensource") @PropertySource (value = "Classpath:resource.properties") public class resource { private String name; Private String WebSite; Private String language; Omit getter, setter method}
Attention:
Test Class (Resourcecontroller.java):
/** * @author OYC * @Title: * @Description: * @date 2018/6/1321:44 * * * @RestController @requestmapping ("/resource") public CLA SS Resourcecontroller { @Autowired private Resource Resource; @RequestMapping ("/getresource") public String getresource () { return "Name:" + resource.getname () + "---- WebSite: "+ resource.getwebsite () +"----Language: "+ resource.getlanguage ();} }
Add @componentscan (basepackages= {"Com.bestoyc"}) to Springdemoapplication to scan the test class methods in our test controller package:
Access: Http://localhost:8080/resource/getResource will get Name:java----WebSite:www.bestoyc.com----Language:java
Spring Boot Starter Series III (Resource file property configuration)