以添加一个媒体类型给日志记录为例
ygo.log.visible-content-type:application/test,application/test2
1、创建属性文件
/**
* 日志属性配置
*
* @author jacksony
* @since 1.2.0
*/
@Configuration
@ConfigurationProperties(prefix = "ygo.log")
public class LoggingProperties {
/**
* 可见的的contentType,多个以逗号分隔
*/
@Getter
@Setter
private String visibleContentType;
}
2、创建需要为bean的门面类
/**
* 可见的contentType门面
*
* @author jacksony
* @since 1.0.2
*/
public class VisibleContentTypeFacade {
@Getter(AccessLevel.PRIVATE)
private List<MediaType> mediaTypes;
public VisibleContentTypeFacade(String visibleContentType) {
mediaTypes = new ArrayList<>();
mediaTypes.addAll(VisibleContentType.defaultMediaTypes());
addMediaTypeFrom(visibleContentType);
}
private void addMediaTypeFrom(String visibleContentType) {
if (SGStringUtils.isBlank(visibleContentType)) {
return;
}
String[] visibleContentTypes = visibleContentType.split(",");
for (String contentType : visibleContentTypes) {
mediaTypes.add(MediaType.valueOf(contentType));
}
}
/**
* 判断request.contentType是否为允许的MediaType类型
* 如果是get类型则没有contentType
* 如果是单元测试可能走Exception分支
*
* @param request http请求
* @return true or false
*/
public boolean isContentTypeVisible(HttpServletRequest request) {
try {
if (request == null || request.getContentType() == null) {
return true;
}
return isContentTypeVisible(MediaType.valueOf(request.getContentType()));
} catch (Exception ex) {
return false;
}
}
/**
* 判断contentType是否为允许的MediaType类型
* 如果是get类型则没有contentType
* 如果是单元测试可能走Exception分支
*
* @param mediaType MediaType类型的contentType
* @return true or false
*/
public boolean isContentTypeVisible(MediaType mediaType) {
boolean visible = false;
for (MediaType type : getMediaTypes()) {
if (type.includes(mediaType)) {
visible = true;
}
}
return visible;
}
}
3、创建配置文件
创建门面类VisibleContentTypeFacade 的bean
/**
* 日志配置
*
* @author jacksony
* @since 1.2.0
*/
@Configuration
public class LoggingConfiguration {
/**
* 可见ContentType门面类
* @param loggingProperties 日志配置属性
* @return 可见ContentType门面类
*/
@Bean
public VisibleContentTypeFacade visibleContentTypeFacade(LoggingProperties loggingProperties) {
return new VisibleContentTypeFacade(loggingProperties.getVisibleContentType());
}
}
4、实际应用
@Autowired
public VisibleContentTypeFacade visibleContentTypeFacade;
//函数里面调用
val mediaType = MediaType.valueOf(response.getContentType() == null ? MediaType.ALL_VALUE :
response.getContentType());
boolean visible = visibleContentTypeFacade.isContentTypeVisible(mediaType);