Azure Functions Java Reference

Java Development Reference for Azure Functions

This document provides a detailed reference for developing Azure Functions using Java. It covers common patterns, best practices, and specific API details.

Core Concepts

Triggers and Bindings

Azure Functions allow you to connect your code to other Azure services and events using triggers and bindings. Triggers define what starts your function, while bindings define how your function interacts with data.

Common Triggers:

Common Bindings:

Function Programming Model

Project Structure

A typical Java Azure Functions project has the following structure:


my-function-app/
├── src/
│   └── main/
│       └── java/
│           └── com/
│               └── example/
│                   └── functions/
│                       ├── Function.java
│                       └── MyOtherFunction.java
├── pom.xml
└── function.json (or host.json and individual function.json files)
        

Annotations

Java functions use annotations to define triggers, bindings, and function metadata. The primary annotation is @FunctionName.

Example: HTTP Trigger Function
@FunctionName("HttpTriggerJava") public HttpResponseMessage run( @HttpTrigger(name = "req", methods = {HttpMethod.GET, HttpMethod.POST}, authLevel = AuthorizationLevel.FUNCTION) HttpRequestMessage> request, final ExecutionContext context) { // Function logic here context.getLogger().info("Java HTTP trigger processed a request."); String name = request.getBody().orElse(""); String responseMessage = String.format("Hello, %s. This HTTP triggered function executed successfully.", name); return request.createResponseBuilder(HttpStatus.OK).body(responseMessage).build(); }

HttpRequestMessage and HttpResponseMessage

For HTTP triggers, you'll interact with HttpRequestMessage to access request details (headers, body, query parameters) and HttpResponseMessage to construct the response.

ExecutionContext

The ExecutionContext provides access to logging and other runtime information.

Common Bindings in Java

Blob Storage Binding

Input Binding: Reads a blob.

@FunctionName("BlobTriggerJava") public void run( @BlobTrigger(name = "inputBlob", path = "samples-workitems/{name}.txt", connection = "AzureWebJobsStorage") String blobContent, @BindingName("name") String blobName, final ExecutionContext context) { context.getLogger().info("Java Blob trigger function processed a blob\n Name: " + blobName + "\n Size: " + blobContent.length() + " Bytes"); }

Output Binding: Writes a blob.

@FunctionName("BlobOutputJava") @SendTo(value = "output-container/{name}.txt") public String run( @HttpTrigger(name = "req", methods = {HttpMethod.GET}, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage> request, @BindingName("name") String blobName, final ExecutionContext context) { String content = "Content for " + blobName; context.getLogger().info("Writing content to blob: " + content); return content; }

Queue Storage Binding

Trigger: Processes a message from a queue.

@FunctionName("QueueTriggerJava") public void run( @QueueTrigger(name = "message", connection = "AzureWebJobsStorage") String message, final ExecutionContext context) { context.getLogger().info("Java Queue trigger function processed a message: " + message); }

Output Binding: Sends a message to a queue.

@FunctionName("QueueOutputJava") public void run( @QueueOutput(name = "outputQueueItem", connection = "AzureWebJobsStorage") OutputBinding outputQueueItem, @HttpTrigger(name = "req", methods = {HttpMethod.GET}, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage> request, final ExecutionContext context) { String msg = "New message for queue."; outputQueueItem.setValue(msg); context.getLogger().info("Sent message to queue: " + msg); }

Table Storage Binding

Input Binding: Retrieves an entity.

@FunctionName("TableInputJava") public void run( @TableInput(name = "inputEntity", partitionKey = "myPartition", rowKey = "myRow", connection = "AzureWebJobsStorage") Map inputEntity, final ExecutionContext context) { if (inputEntity != null) { context.getLogger().info("Retrieved entity: " + inputEntity.get("name")); } }

Output Binding: Inserts or merges an entity.

@FunctionName("TableOutputJava") public void run( @HttpTrigger(name = "req", methods = {HttpMethod.POST}, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage> request, @Table(name = "MyTable", partitionKey = "pk", rowKey = "rk", connection = "AzureWebJobsStorage") OutputBinding outputEntity, final ExecutionContext context) { MyEntity entity = request.getBody().orElseThrow(() -> new IllegalArgumentException("Request body is empty")); outputEntity.setValue(entity); context.getLogger().info("Inserted entity into table."); } } // Assuming MyEntity class is defined elsewhere with @PropertyName annotations for table columns
Note: Ensure your pom.xml includes the necessary Azure Functions Java worker dependencies.

Configuration

host.json

The host.json file configures the Functions host. You can set logging levels, extension bundles, and other host-wide settings.


{
  "version": "2.0",
  "logging": {
    "applicationInsights": {
      "samplingSettings": {
        "isEnabled": true,
        "excludedTypes": "Request"
      }
    }
  },
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[3.3.0, 4.0.0)"
  }
}
        

function.json

Each function typically has a function.json file that defines its triggers and bindings. When using annotations in Java, these are often generated automatically, but you can also define them manually.


{
  "scriptFile": "../bin/com/example/functions/HttpTriggerJava.class",
  "entryPoint": "run",
  "bindings": [
    {
      "authLevel": "function",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    }
  ]
}
        

Dependencies

You'll typically manage dependencies using Maven. Add the following to your pom.xml:


<dependency>
    <groupId>com.microsoft.azure.functions</groupId>
    <artifactId>azure-functions-java-library</artifactId>
    <version>1.4.0</version> <!-- Use the latest version -->
</dependency>
        

Best Practices

  • Statelessness: Design your functions to be stateless. Avoid storing state within the function instance.
  • Error Handling: Implement robust error handling and logging.
  • Idempotency: For non-HTTP triggers, ensure your functions are idempotent to handle retries safely.
  • Configuration: Use application settings for connection strings and other configurable values.
  • Dependencies: Keep your dependencies lean to minimize cold start times.
Important: Always refer to the official Azure Functions documentation for the most up-to-date information on API versions, bindings, and features.