我建议创建2个不同的控制器。每个人对自己的个人资料
@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
注意th在'resolveEmbeddedValuesInPatterns(requestMapping.path())'返回一个数组,所以我们应该访问第一个项目来添加前缀: '.paths(prefix + resolveEmbeddedValuesInPatterns(requestMapping.path())[0])' 谢谢! – angeldev
我会说我们应该添加前缀到数组中的所有项目。如果有多个映射指向相同的控制器方法,我们应该调整所有的映射。 – StanislavL