DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Cloud Key Management Services Use Cases
  • Migrating Spring Java Applications to Azure App Service (Part 1: DataSources and Credentials)
  • Distributed Tracing System (Spring Cloud Sleuth + OpenZipkin)
  • Component Tests for Spring Cloud Microservices

Trending

  • Grounding AI Agents in Governed Data
  • How to Format Articles for DZone
  • What Cloud Engineers Actually Need to Know About AI Infrastructure
  • Who Should Grade Your AI? Rules vs LLM Judges vs Humans

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Software Design and Architecture
  3. Cloud Architecture
  4. Spring Cloud Function in Azure

Spring Cloud Function in Azure

This article outlines the deployment of Spring Cloud Function as a Java Function to Azure Functions, from validation and setup to testing and deployment.

By 
Vignesh Prabhu
·
Feb. 02, 21 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
8.5K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

This article covers the usage of Spring Cloud Function as a Java Function and deployment to Azure Functions.  

Prerequisites

  • JDK, version 8+.
  • Apache Maven, version 3 or higher.
  • Azure Account (free trial would suffice as well).
  • Azure CLI.
  • Azure Functions Core Tools.

Validating the Local Environment Setup

Verify Apache Maven version:

PowerShell
 




x


 
1
mvn -V



Verify Azure CLI: 

PowerShell
 




xxxxxxxxxx
1


 
1
az --version



Verify Azure Function Core tools: 

PowerShell
 




xxxxxxxxxx
1


 
1
func -v



Code Setup

Create an empty maven project. Use the below pom.xml and build the project.

XML
 




x


 
1
<?xml version="1.0" encoding="UTF-8"?>
2
<project xmlns="http://maven.apache.org/POM/4.0.0"
3
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5
    <modelVersion>4.0.0</modelVersion>
6

          
7
    <groupId>com.demo</groupId>
8
    <artifactId>demo-springcloud-function</artifactId>
9
    <version>1.0-SNAPSHOT</version>
10
    <packaging>jar</packaging>
11

          
12
    <name>Helloworld Spring Function on Azure</name>
13

          
14
    <parent>
15
        <groupId>org.springframework.boot</groupId>
16
        <artifactId>spring-boot-starter-parent</artifactId>
17
        <version>2.4.2</version>
18
        <relativePath/> <!-- lookup parent from repository -->
19
    </parent>
20
    <properties>
21
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
22
        <maven.compiler.source>1.8</maven.compiler.source>
23
        <maven.compiler.target>1.8</maven.compiler.target>
24
        <azure.functions.java.library.version>1.4.0</azure.functions.java.library.version>
25
        <azure.functions.maven.plugin.version>1.3.1</azure.functions.maven.plugin.version>
26
        <functionResourceGroup>sample-resource-group</functionResourceGroup>
27
        <functionAppName>helloworld-spring-function</functionAppName>
28
        <functionAppRegion>westeurope</functionAppRegion>
29
        <stagingDirectory>${project.build.directory}/azure-functions/${functionAppName}</stagingDirectory>
30
        <start-class>com.demo.HelloworldApplication</start-class>
31
        <spring.boot.wrapper.version>1.0.26.RELEASE</spring.boot.wrapper.version>
32
    </properties>
33

          
34
    <dependencies>
35
        <dependency>
36
            <groupId>org.springframework.cloud</groupId>
37
            <artifactId>spring-cloud-function-adapter-azure</artifactId>
38
        </dependency>
39
        <dependency>
40
            <groupId>org.springframework.cloud</groupId>
41
            <artifactId>spring-cloud-starter-function-webflux</artifactId>
42
            <scope>provided</scope>
43
        </dependency>
44
        <!-- Test -->
45
        <dependency>
46
            <groupId>org.springframework.boot</groupId>
47
            <artifactId>spring-boot-starter-test</artifactId>
48
            <scope>test</scope>
49
        </dependency>
50
        <dependency>
51
            <groupId>org.junit.jupiter</groupId>
52
            <artifactId>junit-jupiter-api</artifactId>
53
            <version>5.7.0</version>
54
            <scope>test</scope>
55
        </dependency>
56
        <dependency>
57
            <groupId>io.gatling.highcharts</groupId>
58
            <artifactId>gatling-charts-highcharts</artifactId>
59
            <version>3.5.0</version>
60
            <scope>test</scope>
61
        </dependency>
62
    </dependencies>
63
    <dependencyManagement>
64
        <dependencies>
65
            <dependency>
66
                <groupId>org.springframework.cloud</groupId>
67
                <artifactId>spring-cloud-function-dependencies</artifactId>
68
                <version>3.1.0</version>
69
                <type>pom</type>
70
                <scope>import</scope>
71
            </dependency>
72
            <dependency>
73
                <groupId>com.microsoft.azure.functions</groupId>
74
                <artifactId>azure-functions-java-library</artifactId>
75
                <version>${azure.functions.java.library.version}</version>
76
            </dependency>
77
        </dependencies>
78
    </dependencyManagement>
79

          
80
<build>
81
    <plugins>
82
        <plugin>
83
            <groupId>com.microsoft.azure</groupId>
84
            <artifactId>azure-functions-maven-plugin</artifactId>
85
            <configuration>
86
                <appName>${functionAppName}</appName>
87
                <resourceGroup>${functionResourceGroup}</resourceGroup>
88
                <appServicePlanName>azure-functions-app-service-plan</appServicePlanName>
89
                <region>${functionAppRegion}</region>
90
                <runtime>
91
                    <os>windows</os>
92
                </runtime>
93
                <appSettings>
94
                    <property>
95
                        <name>FUNCTIONS_EXTENSION_VERSION</name>
96
                        <value>~3</value>
97
                    </property>
98
                </appSettings>
99
            </configuration>
100
            <executions>
101
                <execution>
102
                    <id>package-functions</id>
103
                    <goals>
104
                        <goal>package</goal>
105
                    </goals>
106
                </execution>
107
            </executions>
108
        </plugin>
109
        <plugin>
110
            <groupId>org.apache.maven.plugins</groupId>
111
            <artifactId>maven-resources-plugin</artifactId>
112
            <executions>
113
                <execution>
114
                    <id>copy-resources</id>
115
                    <phase>package</phase>
116
                    <goals>
117
                        <goal>copy-resources</goal>
118
                    </goals>
119
                    <configuration>
120
                        <overwrite>true</overwrite>
121
                        <outputDirectory>${stagingDirectory}</outputDirectory>
122
                        <resources>
123
                            <resource>
124
                                <directory>${project.basedir}</directory>
125
                                <includes>
126
                                    <include>host.json</include>
127
                                    <include>local.settings.json</include>
128
                                </includes>
129
                            </resource>
130
                        </resources>
131
                    </configuration>
132
                </execution>
133
            </executions>
134
        </plugin>
135
        <plugin>
136
            <groupId>org.apache.maven.plugins</groupId>
137
            <artifactId>maven-dependency-plugin</artifactId>
138
            <executions>
139
                <execution>
140
                    <id>copy-dependencies</id>
141
                    <phase>prepare-package</phase>
142
                    <goals>
143
                        <goal>copy-dependencies</goal>
144
                    </goals>
145
                    <configuration>
146
                        <outputDirectory>${stagingDirectory}/lib</outputDirectory>
147
                        <overWriteReleases>false</overWriteReleases>
148
                        <overWriteSnapshots>false</overWriteSnapshots>
149
                        <overWriteIfNewer>true</overWriteIfNewer>
150
                        <includeScope>runtime</includeScope>
151
                        <excludeArtifactIds>azure-functions-java-library</excludeArtifactIds>
152
                    </configuration>
153
                </execution>
154
            </executions>
155
        </plugin>
156
        <plugin>
157
            <artifactId>maven-clean-plugin</artifactId>
158
            <version>3.1.0</version>
159
            <configuration>
160
                <filesets>
161
                    <fileset>
162
                        <directory>obj</directory>
163
                    </fileset>
164
                </filesets>
165
            </configuration>
166
        </plugin>
167
    </plugins>
168
</build>
169
</project>



Customize below properties in the pom.xml file as per your application.

<functionAppName> — name of your Azure Function

<functionAppRegion> — name of the Azure region where your Function will be deployed

<functionResourceGroup> — name of the Azure resource group which will be used


In the Project base directory create the following configuration files required by the Azure Functions.

host.json

JSON
 




xxxxxxxxxx
1


 
1
{
2
  "version": "2.0",
3
  "extensionBundle": {
4
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
5
    "version": "[1.*, 2.0.0)"
6
  } 
7
}



local.settings.json

JSON
 




xxxxxxxxxx
1
12


 
1
{
2
  "IsEncrypted": false,
3
  "Values": {
4
    "AzureWebJobsStorage": "",
5
    "FUNCTIONS_WORKER_RUNTIME": "java"
6
  },
7
  "Host": {
8
    "LocalHttpPort": 8091,
9
    "CORS": "*",
10
    "CORSCredentials": false
11
  }
12
}



Create below Model Classes.

Employee.java

Java
 




xxxxxxxxxx
1
20


 
1
package com.demo.model;
2

          
3
import jdk.nashorn.internal.objects.annotations.Getter;
4

          
5
public class Employee {
6
    private String name;
7

          
8
    public Employee(String name) {
9
        this.name = name;
10
    }
11

          
12
    public String getName() {
13
        return name;
14
    }
15

          
16
    public void setName(String name) {
17
        this.name = name;
18
    }
19
}
20

          



EmployeeGreeting.java

Java
 




x



1
package com.demo.model;
2

          
3
public class EmployeeGreeting {
4
    private String message;
5

          
6
    public EmployeeGreeting(String message) {
7
        this.message = message;
8
    }
9

          
10
    public String getMessage() {
11
        return message;
12
    }
13

          
14
    public void setMessage(String message) {
15
        this.message = message;
16
    }
17
}
18

          



Create the Springboot Application

The welcomeEmployee() function returns a java.util.function.Function and is a Spring bean. It is important that the Azure Functions that we create next will have the same name.

welcomeEmployee

Java
 




xxxxxxxxxx
1
21


 
1
package com.demo;
2

          
3
import com.demo.model.Employee;
4
import com.demo.model.EmployeeGreeting;
5
import org.springframework.boot.SpringApplication;
6
import org.springframework.boot.autoconfigure.SpringBootApplication;
7
import org.springframework.context.annotation.Bean;
8
import java.util.function.Function;
9

          
10
@SpringBootApplication
11
public class HelloworldApplication {
12
    public static void main(String[] args) throws Exception {
13
        SpringApplication.run(HelloworldApplication.class, args);
14
    }
15

          
16
    @Bean
17
    public Function<Employee, EmployeeGreeting> welcomeEmployee() {
18
        return employee -> new EmployeeGreeting("Hello, We welcome you , " + employee.getName());
19
    }
20
}



Create the Azure Function

  • The Java class which is an Azure Function extends the AzureSpringBootRequestHandler, does the link between Azure Functions and Spring Cloud Function. This is what provides the handleRequest() method that is used in its execute() method.
  • The name of the function, defined with @FunctionName("welcomeEmployee") annotation, is the same as the Spring bean we have configured in the previous step, welcomeEmployee 
Java
 




xxxxxxxxxx
1
26


 
1
package com.demo;
2
import com.demo.model.Employee;
3
import com.demo.model.EmployeeGreeting;
4
import com.microsoft.azure.functions.*;
5
import com.microsoft.azure.functions.annotation.AuthorizationLevel;
6
import com.microsoft.azure.functions.annotation.FunctionName;
7
import com.microsoft.azure.functions.annotation.HttpTrigger;
8
import org.springframework.cloud.function.adapter.azure.AzureSpringBootRequestHandler;
9
import java.util.Optional;
10

          
11
public class HelloWorldHandler extends AzureSpringBootRequestHandler<Employee, EmployeeGreeting> {
12

          
13
    @FunctionName("welcomeEmployee")
14
    public HttpResponseMessage execute(
15
            @HttpTrigger(name = "request", methods = {HttpMethod.GET, HttpMethod.POST},authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Optional<Employee>> request,ExecutionContext context) {
16
       
17
        return request
18
                .createResponseBuilder(HttpStatus.OK)
19
                .body(handleRequest(request.getBody().get(), context))
20
                .header("Content-Type", "application/json")
21
                .build();
22
    }
23
}
24

          



Local Testing

Package the application:

PowerShell
 




xxxxxxxxxx
1


 
1
mvn clean package



Run the project locally: 

PowerShell
 




xxxxxxxxxx
1


 
1
mvn azure-functions:run



Below will be the output in the console on successful startup: 

successful output

Successful output in the console

Test the setup using Postman:

postman setup test

Verify setup in Postman

Deployment to Azure Function

In the command line, run the below command and login to the Azure account.

PowerShell
 




xxxxxxxxxx
1


 
1
az login



Deploy to Azure function using below command: 

PowerShell
 




xxxxxxxxxx
1


 
1
mvn azure-functions:deploy


what should appear in the consol

Expected console output after above command


Verify the deployment by logging into the Azure Portal:

Azure portal

Azure portal homepage


Test the Azure function by using Postman:

postman to test function

Use Postman to test Azure function


azure Spring Cloud Spring Framework

Opinions expressed by DZone contributors are their own.

Related

  • Cloud Key Management Services Use Cases
  • Migrating Spring Java Applications to Azure App Service (Part 1: DataSources and Credentials)
  • Distributed Tracing System (Spring Cloud Sleuth + OpenZipkin)
  • Component Tests for Spring Cloud Microservices

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook