javaazure-functionssingletonservice-layer

Using service layer functions in a java project without spring


I am writing an azure function in java. To use a good modular pattern I created a service layer which has abstract interface classes and an impl layer that implements the service layer.

However, I am not using Spring-framework so I can't use @Autowired to create a singleton instance of the service layer in the runner file. How can I use my service layer functions in my runner class (or other places in my project)?

Service Layer

public interface TimeTriggeredService {

  String getLogs(String token, String url,final ExecutionContext context);
}

Impl Layer

public class TimeTriggeredServiceImpl implements TimeTriggeredService {

  public String getLogs(String token, String url,final ExecutionContext context) {
    // Some logic
  }
}

Runner Class

public class TimeTriggeredFunction {

  @FunctionName("TimeTriggeredFunction")
  public void run(@TimerTrigger(name = "timerInfo", schedule = "0 */1 * * * *") String timerInfo,
      final ExecutionContext context) {
    
    String timeAuditLogs = TimeTriggeredService.getLogs(token, URL ,context);  // unsure what should replace this line or what should be done before this. 
  }
}

Note : This is NOT a spring project.


Solution

  • Dependency Injection for Java is not supported yet. Check out GitHub issue around the same: #324.

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

    Here is a sample of how to use it.

    If you do not want to use Spring framework, you will have to create a global instance in the class and use it.