ale*_*oid 8 java spring application-settings spring-boot
我可以使用启用/禁用整个@RestController功能@ConditionalOnProperty,例如:
@RestController
@ConditionalOnProperty(name = "com.example.api.controller.decision.DecisionController.enabled", havingValue = "true")
@RequestMapping("/v1.0/decisions")
public class DecisionController {
}
Run Code Online (Sandbox Code Playgroud)
以下配置可以正常工作。但是我需要对此控制器进行更细粒度的控制,并启用/禁用对其中某些方法的访问,例如:
@RestController
@ConditionalOnProperty(name = "com.example.api.controller.decision.DecisionController.enabled", havingValue = "true")
@RequestMapping("/v1.0/decisions")
public class DecisionController {
@ConditionalOnProperty(name = "com.example.api.controller.decision.DecisionController.create.enabled", havingValue = "true")
@PreAuthorize("isAuthenticated()")
@RequestMapping(method = RequestMethod.POST)
public DecisionResponse create(@Valid @RequestBody CreateDecisionRequest request, Authentication authentication) {
...
}
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我已添加@ConditionalOnProperty到createmethod中,但这种方法不起作用,即使启用DecisionController了该create方法,即使com.example.api.controller.decision.DecisionController.create.enabledmy中没有属性也可以启用该方法application.properties。
create在这种情况下如何正确启用/禁用方法?
您还可以使用 aop 不继续执行方法并向用户返回一些状态。我在这里使用注释来标记/识别禁用的方法。如果您想根据属性中的某些值禁用,您可以向该注释添加属性。就像您可以添加相同的属性名称和具有值并查找这些等等...
@Retention(RUNTIME)
@Target(METHOD)
public @interface DisableMe {}
Run Code Online (Sandbox Code Playgroud)
方面:
@Aspect
@Component
public class DisableCertainAPI {
@Autowired private HttpServletResponse httpServletResponse;
@Pointcut(" @annotation(disableMe)")
protected void disabledMethods(DisableMe disableMe) {
// disabled methods pointcut
}
@Around("disabledMethods(disableMe)")
public void dontRun(JoinPoint jp, DisableMe disableMe) throws IOException {
httpServletResponse.sendError(HttpStatus.NOT_FOUND.value(), "Not found");
}
}
Run Code Online (Sandbox Code Playgroud)
和目标方法:
@DisableMe
@GetMapping(...)
public ResponseEntity<String> doSomething(...){
logger.info("recieved a request");
}
Run Code Online (Sandbox Code Playgroud)
你会看到这样的回应:
{
"timestamp": "2019-11-11T16:29:31.454+0000",
"status": 404,
"error": "Not Found",
"message": "Not found",
"path": "/xyz/...."
}
Run Code Online (Sandbox Code Playgroud)
\n\n\n不幸的是,@ConditionalOnProperty注释不能在单个@RequestMapping方法上使用\xe2\x80\x99。作为解决方法,您可以将所需的映射移至单独的控制器 bean。
\n
http://dolszewski.com/spring/feature-toggle-spring-boot/
\n\n我希望这可以帮助那些因同一问题来到此页面的人。
\n| 归档时间: |
|
| 查看次数: |
1532 次 |
| 最近记录: |