非Spring Boot项目:如何读取azure-maven-plugin的appSettings及设置环境变量?
一、读取azure-maven-plugin中的属性值
你用System.getProperty()读取失败的核心原因是:<appSettings>里的配置是Azure Functions应用的运行时设置,并非JVM系统属性,所以本地直接调用System.getProperty()无法获取到这些值。针对不同运行场景,有以下解决方案:
1. 本地运行Azure Functions时读取
azure-functions-maven-plugin执行azure-functions:run时,会自动将<appSettings>中的配置同步到项目根目录local.settings.json的Values节点下。你可以直接读取这个JSON文件获取配置:
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.File; public class AppSettingsReader { public static String getAppSetting(String key) throws Exception { ObjectMapper mapper = new ObjectMapper(); JsonNode root = mapper.readTree(new File("local.settings.json")); return root.path("Values").path(key).asText(); } // 使用示例 public static void main(String[] args) throws Exception { String extensionVersion = getAppSetting("FUNCTIONS_EXTENSION_VERSION"); System.out.println(extensionVersion); } }
2. Azure云端运行时读取
当函数部署到Azure后,<appSettings>中的配置会自动转为函数应用的环境变量,此时可以通过System.getenv()方法读取:
String extensionVersion = System.getenv("FUNCTIONS_EXTENSION_VERSION");
3. 构建阶段将配置注入为JVM系统属性
如果需要在本地构建或运行时直接通过System.getProperty()获取,可以在Maven插件的执行配置中添加systemPropertyVariables,将<appSettings>的值映射为系统属性:
<plugin> <groupId>com.microsoft.azure</groupId> <artifactId>azure-functions-maven-plugin</artifactId> <version>${azure.functions.maven.plugin.version}</version> <configuration> <!-- 原有配置不变 --> <appSettings> <property> <name>FUNCTIONS_EXTENSION_VERSION</name> <value>~4</value> </property> </appSettings> </configuration> <executions> <execution> <id>package-functions</id> <goals> <goal>package</goal> </goals> <configuration> <systemPropertyVariables> <FUNCTIONS_EXTENSION_VERSION>${FUNCTIONS_EXTENSION_VERSION}</FUNCTIONS_EXTENSION_VERSION> </systemPropertyVariables> </configuration> </execution> </executions> </plugin>
之后运行时就能通过System.getProperty("FUNCTIONS_EXTENSION_VERSION")获取到对应值。
二、在azure-maven-plugin中设置环境变量
azure-functions-maven-plugin的<appSettings>配置本质就是用来设置Azure Functions应用的运行时环境变量:
- 本地运行:插件会将
<appSettings>同步到local.settings.json,函数运行时会自动加载这些作为环境变量。 - 云端部署:这些配置会被上传到Azure Functions应用的「应用设置」中,作为云端运行时的环境变量。
如果需要在Maven构建过程中设置环境变量(而非函数运行时),可以使用exec-maven-plugin插件配合environmentVariables配置,或者直接在Maven命令中通过export VAR=value && mvn ...(Linux/macOS)或set VAR=value && mvn ...(Windows)的方式传递。
内容的提问来源于stack exchange,提问作者ng.newbie

