一、资源文件中的属性配置与映射到实体类
1、首先在pom.xml文件中开启资源文件的配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
2、在src/main/resources文件夹中,新建resource.properties文件。

3、在src/main/java中新建包com.imooc.pojo,并新建Resource.java

重点是是加入@Configuration、@ConfigurationProperties、@PropertySource三个注解。
@ConfigurationProperties(prefix = "com.imooc.opensource"),中prefix代表前缀,是对应resource.properties文件中的前缀名称
@PropertySource(value = "classpath:resource.properties")中value代表资源文件的路径及资源文件名。
4、在src/main/java中新建包com.imooc.controller,并新建ResourceController.java

6、附件:pojo文件中的IMoocJSONResult.java工具类
package com.imooc.pojo;
import com.fasterxml.jackson.databind.ObjectMapper;
public class IMoocJSONResult {
// 定义 jackson 对象
private static final ObjectMapper MAPPER = new ObjectMapper();
// 响应业务状态
private Integer status;
// 响应消息
private String msg;
// 响应中的数据
private Object data;
private String ok; // 不使用
public static IMoocJSONResult build(Integer status, String msg, Object data) {
return new IMoocJSONResult(status, msg, data);
}
public static IMoocJSONResult ok(Object data) {
return new IMoocJSONResult(data);
}
public IMoocJSONResult(Integer status, String msg, Object data) {
this.status = status;
this.msg = msg;
this.data = data;
}
public IMoocJSONResult(Object data) {
this.status = 200;
this.msg = "OK";
this.data = data;
}
public IMoocJSONResult() {
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
二、springboot 资源文件配置server


附源码地址:https://github.com/leechenxiang/imooc-springboot-starter
网友评论