First, the core configuration file
The core configuration file is application.properties or application.yml configuration file in the root directory of resources.
We also write custom configuration generally written in this file, but in fact we have to distinguish between convenience and management, we can create a properties file yourself, to note that, if you application.properties or application.yml also written on the inside the same configuration, springboot will give priority to read application.properties application.yml in configuration or.
Second, read the custom configuration file
Here I created a new school.properties in the resource directory
school.name=加里敦大学
school.address=阿拉斯加
school.age=100
A read mode: adding annotation on the corresponding variable @value
package com.rong.controller;
import com.rong.config.ConfigInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ConfigInfoController {
/**
* 读取自定义配置的方式一
*/
@Value("${school.name}")
private String name;
@Value("${school.address}")
private String address;
@Value("${school.age}")
private int age;
@GetMapping("/inits")
private String initConfigInfo1(){
return name + " " + address + " " + age;
}
}
Here to visit localhost: 8080 / inits get Jiali Dun University of Alaska 100
Read way:
We need to write a configuration class
package com.rong.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
/**
* 作为配置类
*/
@Component//会将该类的对象加入到容器中
@PropertySource(value = "classpath:myschool.properties")//指定外部配置文件的名字
@ConfigurationProperties(prefix = "school")//表示会从配置文件中读取以school开头的内容
public class ConfigInfo {
private String name;
private String address;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Then controller in use after automatic injection @Autowired
package com.rong.controller;
import com.rong.config.ConfigInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ConfigInfoController {
/**
* 读取自定义配置的方式二
*/
@Autowired
private ConfigInfo configInfo;
@GetMapping("/init")
public String initConfigInfo2() {
return configInfo.getName();
}
}
Here I only returns the name, namely access localhost: 8080 / init can get "Jiali Dun University" the