欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

在 WebEndpointProperties 类中阅读 Java 的文章(附演示) - 1.基础知识

最编程 2024-04-17 08:39:19
...

Spring Boot 的配置类 WebEndpointProperties,用于配置 Web 端点(endpoints)的相关属性

先看其源码类:

package org.springframework.boot.actuate.autoconfigure.endpoint.web;

import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
@Configu
rationProperties(prefix = "management.endpoints.web")
public class WebEndpointProperties {

	private final Exposure exposure = new Exposure();

	/**
	 * Base path for Web endpoints. Relative to server.servlet.context-path or
	 * management.server.servlet.context-path if management.server.port is configured.
	 */
	private String basePath = "/actuator";

	/**
	 * Mapping between endpoint IDs and the path that should expose them.
	 */
	private final Map<String, String> pathMapping = new LinkedHashMap<>();

	public Exposure getExposure() {
		return this.exposure;
	}

	public String getBasePath() {
		return this.basePath;
	}

	public void setBasePath(String basePath) {
		Assert.isTrue(basePath.isEmpty() || basePath.startsWith("/"), "Base path must start with '/' or be empty");
		this.basePath = cleanBasePath(basePath);
	}

	private String cleanBasePath(String basePath) {
		if (StringUtils.hasText(basePath) && basePath.endsWith("/")) {
			return basePath.substring(0, basePath.length() - 1);
		}
		return basePath;
	}

	public Map<String, String> getPathMapping() {
		return this.pathMapping;
	}

	public static class Exposure {

		/**
		 * Endpoint IDs that should be included or '*' for all.
		 */
		private Set<String> include = new LinkedHashSet<>();

		/**
		 * Endpoint IDs that should be excluded or '*' for all.
		 */
		private Set<String> exclude = new LinkedHashSet<>();

		public Set<String> getInclude() {
			return this.include;
		}

		public void setInclude(Set<String> include) {
			this.include = include;
		}

		public Set<String> getExclude() {
			return this.exclude;
		}

		public void setExclude(Set<String> exclude) {
			this.exclude = exclude;
		}

	}

}

解读上述源码的大致细节

  • @ConfigurationProperties(prefix = "management.endpoints.web"):注解表明这个类将会绑定以 management.endpoints.web 开头的配置属性
    配置文件(比如 application.propertiesapplication.yml)中,可以设置以 management.endpoints.web 为前缀的属性,Spring Boot 将会自动将这些属性注入到这个类的实例中

  • Exposure 内部静态类:定义 Web 端点的暴露(exposure)策略,包含了两个属性 include 和 exclude,分别表示应该包含哪些端点和排除哪些端点

  • basePath 属性:指定 Web 端点的基本路径,默认值为 "/actuator",所有的端点都会在 "/actuator" 这个路径下暴露。

  • pathMapping 属性:自定义端点的路径映射,可以将端点 ID 映射到自定义的路径上

一般接口的使用方式可以使用配置文件(以下为例子)

management.endpoints.web.base-path=/custom-path
management.endpoints.web.exposure.include=health,info
management.endpoints.web.path-mapping.health=/custom-health

推荐阅读