Search code examples
spring-dataspring-cloud-function

Injecting spring data repository into spring cloud function


I would like to use spring data repository functionality within the spring cloud function.

I've cloned the spring cloud function with azure provider: https://github.com/spring-cloud/spring-cloud-function/tree/2.2.x/spring-cloud-function-samples/function-sample-azure

I have it running locally as well as on azure.

I would like to do the following:

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);
    }

}

Example mongo repo:

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

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

The result is NullPointerException. Any idea whether it's possible with spring cloud functions?


Solution

  • You are injecting it in the wrong place. FooHandler is just a delegate to invoke uppercase function. So instead inject it into the function itself.

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