首页 > 解决方案 > 将spring数据存储库注入spring cloud函数

问题描述

我想在 spring 云功能中使用 spring 数据存储库功能。

我已经使用 azure 提供程序克隆了 spring 云功能:https ://github.com/spring-cloud/spring-cloud-function/tree/2.2.x/spring-cloud-function-samples/function-sample-azure

我让它在本地和天蓝色上运行。

我想做以下事情:

public class FooHandler extends AzureSpringBootRequestHandler<Foo, Bar> {

    @Autowired
    private FooRepository fooRepository;

    @FunctionName("uppercase")
    public Bar execute(
        @HttpTrigger(name = "req", methods = { HttpMethod.POST}, authLevel = AuthorizationLevel.FUNCTION) HttpRequestMessage<Optional<Foo>> foo,
        ExecutionContext context) {
        fooRepository.insert(foo.getBody().get());      
        return handleRequest(foo.getBody().get(), context);
    }

}

示例 mongo 存储库:

import org.springframework.data.mongodb.repository.MongoRepository;

public interface FooRepository extends MongoRepository<Foo, String> {
}

结果是 NullPointerException。知道弹簧云功能是否可行吗?

标签: spring-dataspring-cloud-function

解决方案


您将其注入错误的位置。FooHandler 只是一个调用uppercase函数的委托。因此,改为将其注入函数本身。

@Bean
public Function<Foo, Bar> uppercase(FooRepository fooRepository) {
    return foo -> {
        // do whatever you need with fooRepository
        return new Bar(foo.getValue().toUpperCase());
    };
}

推荐阅读