【问题标题】:Enable or disable Spring restful API (endpoint) based on the flag from DB根据来自数据库的标志启用或禁用 Spring restful API(端点)
【发布时间】:2023-02-07 03:18:29
【问题描述】:

我有一个宁静的 API,它必须根据我在应用程序加载期间获取的标志值来启用或禁用。但是我无法使用@Conditional Annotation 启用/禁用 API。我可以通过 @ConditionOnProperty 在 application.properties 文件中设置一个属性来实现这一点。但是,我需要来自数据库的动态值来启用/禁用 API。

Condition class looks like below

@Component
public class CheckCondition implements Condition {

  @Autowired
  private AppProperties appProp;
  
  @Override
  public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
    //Get the Flag value from DB which is fetched from AppProperties
    String value = appProp.getProperty(AppPropertiesEnum.ENABLE_LOGSTASH);
    boolean flag = false;
    if(value != null && value.equalsIgnoreCase("YES"))
      flag = true;
    return flag;
  }
}
Controller class which uses CheckCondition.

@RestController
@CrossOrigin
@Conditional(CheckCondition.class)
public class CheckController {

  private static final String URL_PUT_CHECKS        = "v1/core/checks";              // PUT
  
  @Autowired
  private ContextService serviceContext;
  @Autowired
  private CheckService serviceCheck;
  
  @RequestMapping(value=URL_PUT_CHECKS, method=RequestMethod.PUT)
  public void putLogstash(@RequestBody String jsonValue) {
    serviceCheck.storeValue(request, serviceContext.getAppNameVerified(request), jsonValue);
  }
}

AppProperties 也是一个组件,我在其中进行数据库调用以获取标志以设置条件。 加载应用程序时,首先启动 CheckCondition 类,appProp 将为空。似乎它正在实现条件接口 spring boot 不加载 postProcessor 方法/bean。我尝试为此使用 DependsOn 和 Order。我不确定我错过了什么。

任何建议表示赞赏。提前致谢。

【问题讨论】:

  • 你不能在条件中自动装配,为什么在这里写你自己的条件,因为它似乎只是一个属性,为什么不使用现有的ConditionalOnProperty
  • @M.Deinum 我正在尝试的值将从数据库加载,而不是我可以将其存储在属性文件中的静态值。当我从 Application.properties 文件中读取 ConditionalOnProperty 时,它工作正常。
  • 你可以使用BeanPostProcessor

标签: spring spring-boot java-8 spring-annotations spring-boot-configuration


【解决方案1】:

你可以这样试试。

@RestController
public class TestController {

  @Autowired
  private CheckRepository checkRepository;

  @GetMapping("/test")
  public ResponseEntity<Object> getData() {
    boolean flag = checkRepository.findByName("value");
    if (!flag) {
      return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
    }

  }
}

【讨论】:

    猜你喜欢
    • 2016-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-04
    • 1970-01-01
    • 1970-01-01
    • 2011-02-01
    相关资源
    最近更新 更多