gpt4 book ai didi

java - 根据 spring Activity 配置文件修改映射路径

转载 作者:行者123 更新时间:2023-11-30 02:31:11 25 4
gpt4 key购买 nike

我希望 Controller 的开发和生产环境有不同的映射路线。我已经使用 @ConditionalOnExpression 尝试过此操作,但如果条件为 false,它似乎也会删除 @RequestMapping 注释:

@RestController
@RequestMapping(value = "/dev")
@ConditionalOnExpression("#{environment.getActiveProfiles()[0] == 'DEV'}")
public class CheckoutController {

如果 Activity 配置文件是 DEV,我想向所有映射路由添加前缀“/dev”。

最佳答案

我建议创建 2 个不同的 Controller 。每一项都有自己的个人资料

@RestController
@RequestMapping(value = "/dev")
@ConditionalOnExpression("#{environment.getActiveProfiles()[0] == 'DEV'}")
public class DevCheckoutController {

@RestController
@RequestMapping(value = "/prod")
@ConditionalOnExpression("#{environment.getActiveProfiles()[0] == 'PROD'}")
public class ProdCheckoutController {

另一种(更复杂)的方法是重写RequestMappingHandlerMapping。您需要该方法。

    protected RequestMappingInfo createRequestMappingInfo(
RequestMapping requestMapping, RequestCondition<?> customCondition) {

return RequestMappingInfo
.paths(resolveEmbeddedValuesInPatterns(requestMapping.path()))
.methods(requestMapping.method())
.params(requestMapping.params())
.headers(requestMapping.headers())
.consumes(requestMapping.consumes())
.produces(requestMapping.produces())
.mappingName(requestMapping.name())
.customCondition(customCondition)
.options(this.config)
.build();
}

.paths(resolveEmbeddedValuesInPatterns(requestMapping.path())) 中,只需根据配置文件添加一个值。所以你添加环境

@Autowired
Environment env;

方法应该是这样的

String prefix = "DEV".equals(env.getActiveProfiles()[0]) ? "DEV" : ""
return RequestMappingInfo
.paths(prefix + resolveEmbeddedValuesInPatterns(requestMapping.path()))

另一种方法是仅向映射添加表达式

@RequestMapping(value = "/${my.profile.property:}prod")

对于 DEV 配置文件,只需定义属性

my.profile.property=DEV

关于java - 根据 spring Activity 配置文件修改映射路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44243611/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com