简体   繁体   中英

Dependency Injection (IoC) in JAVA + Azure Functions

I am using an Azure Function written in Java to retrieve the data from REST API and insert it into the mongo database. I'm trying to separate the app into different layers like I usually do for web applications - for now I've only extracted the repository that stores the data in mongo into a separate class, so my function class looks like this (I've omitted triggers, error handlings etc)

public class SensorFunctions {

    @FunctionName("saveSensors")
    public void saveSensors(
        final ExecutionContext context) {
        SensorRepository sensorRepository = new SensorRepository();
        new SensorAPI().retrieveSensors()
            .forEach(sensorRepository::saveSensor);
    }
}

I'd prefer to use some king of IoC mechanism, so I don't have to instantiate repostiory and other classes by myself but I can do something like

public class SensorFunctions {
    @Inject
    SensorRepository sensorRepository;

    @Inject
    SensorAPI sensorAPI;

    @FunctionName("saveSensors")
    public void saveSensors(
        final ExecutionContext context) {
        sensorAPI.retrieveSensors()
            .forEach(sensorRepository::saveSensor);
    }
}

Is it possible with Azure functions? Is so, is it possible to create an automatic configuration or do I need to trigger the configuration of the IoC container manually at the beginning of each function (I will have multiple functions in a single project). As the cost is dependent on the function's computation time, I'd prefer as lightweight solution as possible

For now, you can use Spring Framework to use Azure Function for HTTP requests only (not the bindings.

Here is a sample on how to use it

I know there is a work in progress now to support Dependency injection for Azure Function enter link description here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM