【发布时间】:2018-03-29 17:55:40
【问题描述】:
我需要构建一个小型微服务,它接收 REST 请求并在 Cumulocity 中存储数据(设备、测量等)。
对我来说,从文档中不太清楚如何将 platformApi 轻松注入到我的 Spring Boot 应用程序中。尤其是Scope(TenantScope & UserScope)用法不清楚。
您能否举一个非常简单的“hello-world”示例,如何自动连接 platformApi(例如库存)并在应用程序启动时在租户范围内做某事(打印出所有设备)并使用 RestControler RequestMapping 在用户内做某事范围?
这是一个代码片段:
package c8y.example;
import com.cumulocity.microservice.autoconfigure.MicroserviceApplication;
import com.cumulocity.microservice.context.inject.TenantScope;
import com.cumulocity.sdk.client.inventory.InventoryApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.PostConstruct;
@MicroserviceApplication
@RestController
public class App{
@Autowired
InventoryApi inventoryApi;
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
@PostConstruct
public void init() {
System.out.println("Devices: " + inventoryApi.getManagedObjects());
}
@RequestMapping("devices")
public String greeting() {
return "Devices: " + inventoryApi.getManagedObjects();
}
}
到目前为止,我尝试的所有操作都会导致启动时出现错误,即无法注入 bean,或者它们不在所需的范围内或不在上下文中。 我有一个包含引导凭据的 application.properties。
【问题讨论】:
-
在您使用 MicroserviceApplication 注解时,将内部平台 api 注入到您的项目中。这个注解使用了 EnableMicroservicePlatformInternalApi 注解,它负责实际注入 api。查看实际负责提供不同 API 的 CumulocityClientFeature 类。我认为您收到的错误与另一个问题有关
-
您能否提供一个可行的示例或说明我上面的示例中似乎有什么问题?否则不是很清楚出了什么问题。事实上,仅仅使用微服务注释似乎不足以注入平台 api,因为如果我这样做,我总是会得到与范围相关的错误等。
-
对不起,我在第一条评论中混淆了一些东西。 CumulocityClientFeature 将不同的 API 注册为 bean,可以通过自动装配所需的必要 API 来访问这些 API。所以实际上你的例子是正确的。我认为问题在于从一开始就没有创建上下文,因此当应用程序尝试自动装配时无法检索到,例如库存 API。但这只是我的一个假设,因为我也在努力让它发挥作用......
标签: cumulocity