如何惰性地暴露端点REST?

场景:

  

Spring Boot应用程序应公开其REST端点   仅当发生特定操作时。

Spring中有什么方法可以延迟公开端点,甚至整个HTTP子系统吗?

在Apache CXF中,我们可以执行以下操作:

void exposeEndpoints() {
    EndpointImpl endpoint = new EndpointImpl(cxfBus,serviceImpl);
    endpoint.publish();
}

春季如何做同样的事情?

dn5681 回答:如何惰性地暴露端点REST?

您可以看看@RefreshScope

我将按以下方式定义@RestController bean:

@Configuration
@RefreshScope
public ControllerConfig {

    @Bean
    @ConditionalOnProperty(value = "should.initialize.rest",havingValue = true)
    public SomeController someController(){
        ....
    }

    @Bean
    @ConditionalOnProperty(value = "should.initialize.rest",havingValue = true)
    public SomeOtherController someOtherController(){
        ....
    }
}

,并且如果您在should.initialize.rest中以值为false的属性application.properties启动应用程序:

should.initialize.rest=false

那么您的控制器将不会被注册/初始化。应用程序运行时,您可以将application.properties更新为:

should.initialize.rest=true

并调用/refresh,然后您的ApplicationContext将使用REST控制器重新加载/刷新。您可以在下面找到有关@RefreshScope的更多信息:

,

我在下面提供的解决方案是方法之一,它可能适合您的情况,也可能不合适。 这种情况似乎更多地与设计有关,而不是特定的实现。 我建议您在设计上几乎不要改动。

  1. 按照布尔值将事件存储在数据库或会话中(根据要求)。
  2. 使用AspectJ或Spring自己的AOP创建Aspect。
  3. 使用特定的包切入点创建Before方面。
  4. 在@Before建议中,检查布尔值标志(如果发布条件) 比使用joinpoint.proceed()更令人满意,否则会抛出某种错误,表明服务不可用。

另一种方法是使用方面创建自定义注释。您可以根据需要而不是在整个服务层上使用该批注。 第一种方法的好处是您可以在通用级别上控制,第二种方法可以在服务级别上使用。

,

我建议使用您的HTTP子系统创建一个新的子上下文。像这样:

@Service
public class MyBusinessService {

  @Autowired
  private final ApplicationContext parentContext;

  private AnnotationConfigWebApplicationContext webContext;

  public void myBusinessMethod() {
    this.webContext = new AnnotationConfigWebApplicationContext();
    this.webContext.setParent(parentContext);
    this.webContext.scan("com.mybusiness.service.webcomponents");
    this.webContext.refresh();
    this.webContext.start();
  }

}

免责声明:这是概念验证代码,我没有尝试编译或运行它。但希望足以说明这个概念。

本文链接:https://www.f2er.com/3144684.html

大家都在问