根据弹簧活动配置文件修改映射路径

时间:2017-05-29 13:24:12

标签: java spring spring-boot

我想在开发和生产环境中使用不同的控制器映射路径。我已使用@ConditionalOnExpression尝试了此操作,但如果条件为false,它似乎也会删除@RequestMapping注释:

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

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

1 个答案:

答案 0 :(得分:2)

我建议创建2个不同的控制器。每个人都有自己的个人资料

returns = df.pct_change()

@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()))

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

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