第一种方式:通过@Value注解获取配置文件信息
第二种方式:可以通过Environment的getProperty获取你想要的配置信息
第三种方式:通过prefix定义配置前缀来获取配置文件信息
下面用代码来具体示例
下面的代码为通过prefix定义配置前缀来获取配置文件信息中的实体类。
@Component
@ConfigurationProperties(prefix="threadpool")
public class MyConfig {
private int coreSize;
private String threadNamePrefix;
public int getCoreSize() {
return coreSize;
}
public void setCoreSize(int coreSize) {
this.coreSize = coreSize;
}
public String getThreadNamePrefix() {
return threadNamePrefix;
}
public void setThreadNamePrefix(String threadNamePrefix) {
this.threadNamePrefix = threadNamePrefix;
}
}
下面我们通过一个接口实现以上三种方式获取配置文件中的信息
@RestController
public class HelloController {
//通过@Value获取配置文件信息
@Value("${threadpool.coreSize}")
private int corePoolSize;
//通过 Environment对象获取配置文件信息
@Autowired
private Environment env;
//通过prefix定义配置前缀来获取配置文件信息
@Autowired
private MyConfig myConfig;
@RequestMapping("hello")
public Object sayHello() {
HashMap<String, Object> map = new HashMap<String,Object>();
map.put("coreSize", corePoolSize);
map.put("queueCapacity", env.getProperty("threadpool.queueCapacity"));
map.put("ThreadNamePrefix", myConfig.getThreadNamePrefix());
return map;
}
}
下面用postman测试该接口,结果如下