Java中实现代码仅按需启用(如演示用endpoint)的推荐方案是什么?
演示Endpoint环境隔离方案
无额外配置文件的轻量实现
如果使用Spring栈开发,直接使用@Profile注解是成本最低的方案:
- 给演示Endpoint对应的类或方法添加
@Profile("demo")注解,该Bean只有在激活demo环境配置时才会被Spring容器加载 - 启动服务时添加启动参数
--spring.profiles.active=demo即可开启演示接口,生产环境默认不添加该参数,接口完全不会暴露 - 非Spring项目可以用JVM启动参数控制:启动时添加
-Ddemo.endpoint.enable=true,代码中通过System.getProperty("demo.endpoint.enable")判断是否需要注册该接口,无需额外维护配置文件
Maven Profile实现构建级隔离
如果需要从生产构建产物中完全剔除演示代码,避免误配置导致的接口泄露,可以用Maven Profile实现:
- 在pom.xml中定义多套构建profile
<profiles> <!-- 生产环境默认激活 --> <profile> <id>prod</id> <activation> <activeByDefault>true</activeByDefault> </activation> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <excludes> <!-- 编译阶段直接排除演示代码文件 --> <exclude>**/demo/**/*.java</exclude> </excludes> </configuration> </plugin> </plugins> </build> </profile> <!-- 演示环境profile --> <profile> <id>demo</id> </profile> </profiles>
- 构建时指定profile即可:
- 生产构建执行
mvn clean package,默认用prod profile,产物完全不含演示代码 - 演示构建执行
mvn clean package -Pdemo,产物包含所有演示功能
代码中读取Maven Profile名称的方法
可以通过Maven资源过滤能力将当前激活的profile注入到配置文件,再由代码读取:
- 在pom.xml的每个profile中定义
profile.active属性,默认值设为prod:
<properties> <profile.active>prod</profile.active> </properties>
- 开启资源过滤,在项目配置文件(比如application.properties)中添加占位符:
build.profile=@profile.active@
Maven打包时会自动将@profile.active@替换为当前激活profile对应的值 - 代码中读取该配置项即可做逻辑控制,Spring项目可直接用
@Value("${build.profile}")注入,普通Java项目可通过读取配置文件获取值
注意:构建层面剔除代码的安全性高于运行时条件判断,不存在误配置泄露接口的风险,适合对安全要求高的生产项目。
内容的提问来源于stack exchange,提问作者Noam_I
相关产品推荐
相关产品推荐

