Skip to main content

Java Quick Start

This document describes how to create a Java Spring Boot application from scratch and deploy it to a CloudBase HTTP cloud function.

Prerequisites​

Before you begin, ensure that you have:

  • Installed Java JDK (JDK 8 or later recommended)
  • Installed Maven
  • Have a Tencent Cloud account and have activated the CloudBase service
  • Have a basic knowledge of Spring Boot development

Step 1: Create the project directory​

Create a new directory named helloworld-java and enter the directory:

mkdir helloworld-java
cd helloworld-java

Step 2: Initialize Project Configuration​

Create a pom.xml file to describe project information and dependencies:

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

<groupId>com.example</groupId>
<artifactId>helloworld-java</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>

<name>helloworld-java</name>
<description>Simple hello world sample in Spring Boot</description>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.18</version>
<relativePath/>
</parent>

<properties>
<java.version>8</java.version>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

Step 3: Create a Standard Spring Boot Directory Structure​

mkdir -p src/main/java/com/example/demo
mkdir -p src/main/resources

Step 4: Write the Application Code​

Create the src/main/java/com/example/demo/DemoApplication.java file, which is the entry file of the application:

⚠️ Important: CloudBase HTTP cloud functions must use the default port 9000.

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.util.*;

@SpringBootApplication
@RestController
public class DemoApplication {

private final RestTemplate restTemplate = new RestTemplate();

public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}

@GetMapping("/")
public String hello() {
return "Hello World!";
}

@GetMapping("/myip")
public ResponseEntity<?> getIpInfo() {
try {
// Set CORS headers to allow cross-origin requests
HttpHeaders headers = new HttpHeaders();
headers.set("Access-Control-Allow-Origin", "*");
headers.setContentType(MediaType.APPLICATION_JSON);

// Use RestTemplate to obtain remote data (using ipinfo.io as an example here)
String response = restTemplate.getForObject("https://ipinfo.io", String.class);

return new ResponseEntity<>(response, headers, HttpStatus.OK);
} catch (Exception error) {
System.err.println("Failed to obtain IP information: " + error.getMessage());

Map<String, String> errorResponse = new HashMap<>();
errorResponse.put("error", "Failed to fetch remote data");
errorResponse.put("message", error.getMessage());

return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
}
}

@GetMapping("/health")
public ResponseEntity<Map<String, Object>> health() {
// Health Check Endpoint
Map<String, Object> health = new HashMap<>();
health.put("status", "healthy");
health.put("timestamp", new Date().toInstant().toString());
health.put("version", "1.0.0");

return ResponseEntity.ok()
.header("Content-Type", "application/json")
.body(health);
}

@RequestMapping(value = "/{path:[^\\.]*}")
public ResponseEntity<Map<String, String>> notFound() {
// Error handling: return 404 error for unknown paths
Map<String, String> error = new HashMap<>();
error.put("error", "Not Found");

return ResponseEntity.status(HttpStatus.NOT_FOUND)
.header("Content-Type", "application/json")
.body(error);
}
}

Create the configuration file src/main/resources/application.yml:

# Server Configuration
# The default port for CloudBase HTTP cloud functions must be 9000
server:
port: 9000
address: 0.0.0.0

# Application Configuration
spring:
application:
name: helloworld-java

This code creates a basic Web server that provides the following features:

  • Root path (/): returns "Hello World!" message
  • IP Query (/myip): obtains and returns the client's IP information
  • Health Check (/health): returns service status information
  • Error Handling: returns 404 error for unknown paths

Step 5: Build the Application​

Use Maven to build the application:

mvn clean package

After a successful build, a helloworld-java-1.0.0.jar file will be generated in the target/ directory.

Step 6: Create the Startup Script​

💡 Note:

  • When creating the scf_bootstrap file on windows, it is recommended to use
  • When creating the scf_bootstrap file using vscode on windows, deploying to an HTTP cloud function may result in an error: scf_bootstrap file does not exist
  • This error occurs because the script file contains Windows-style carriage returns (^M), causing Linux to fail to recognize the interpreter path correctly. This is a common issue in WSL

Create the scf_bootstrap file (with no file extension), which is the startup script for CloudBase cloud functions:

#!/bin/bash
java -jar target/helloworld-java-1.0.0.jar

⚠️ Note:

  • The file name must be scf_bootstrap with no extension
  • Ensure the file has execute permissions

Grant execute permissions to the startup script:

chmod +x scf_bootstrap

Step 7: Local Testing (Optional)​

Before deployment, you can test the application locally:

java -jar target/helloworld-java-1.0.0.jar

After successful testing, you can verify in the following ways:

  • Access http://localhost:9000/ to view the Hello World message
  • Access http://localhost:9000/myip to view the IP information
  • Access http://localhost:9000/health to view the health status

Press Ctrl + C to stop the local server.

Step 8: Deploy to CloudBase HTTP cloud function​

Prepare Deployment Files​

Ensure your project directory contains the following standard Spring Boot project structure:

helloworld-java/
├── scf_bootstrap
├── pom.xml
├── src/
│ └── main/
│ ├── java/
│ │ └── com/example/demo/DemoApplication.java
│ └── resources/
│ └── application.yml
└── target/
└── helloworld-java-1.0.0.jar

Deploy via the console​

  1. Log in to TCB/cloud function
  2. Click "New Cloud Function"
  3. Select "HTTP cloud function"
  4. Fill in the function name (such as: helloworld-java)
  5. Select runtime: Java 11
  6. Select the "Local upload" method
  7. Package the project files into a zip file and upload it (Please select the files to package, not the root directory folder)
  8. Click "OK" to complete the deployment

Deploy via CLI​

For details, see Deploy HTTP function via CLI

Package the project​

If you need to package manually, you can use the following command:

# Create zip package (including Maven project structure and build artifacts)
zip -r helloworld-java.zip pom.xml target/helloworld-java-1.0.0.jar scf_bootstrap

Step 9: Access Your Application​

After successful deployment, you can refer to Accessing Cloud Functions via HTTP to set up custom domain access to the

You can test in the following ways:

  • Access the root path to view the Hello World message
  • Access the /myip path to view the IP information
  • Access the /health path to check the service status

Frequently Asked Questions​

Q: Why must port 9000 be used?​

A: CloudBase HTTP cloud functions require the application to listen on port 9000, which is the standard configuration of the platform. In Spring Boot, this can be configured via the server.port=9000 setting in application.yml.

Q: How to view function logs?​

A: On the Cloud Functions page of the CloudBase console, click the function name to go to the details page, where you can view the runtime logs.

Q: Which Java versions are supported?​

A: CloudBase supports Java 11 (Kona JDK). See Runtime Environment Support for details.

Q: How to handle CORS cross-origin issues?​

A: Set CORS-related headers such as Access-Control-Allow-Origin in the response headers, as shown in the example code.

Q: How to handle long function cold startup times?​

A: You can reduce cold startup time by reducing the JAR file size, optimizing Spring Boot configurations, and other methods.

Q: How to change the application port?​

A: Modify the server.port configuration item in the application.yml file, but CloudBase HTTP cloud functions must use port 9000.

Q: Why use Spring Boot instead of a native Java HTTP server?​

A: Spring Boot offers richer features, a better development experience, and stronger ecosystem support, such as dependency injection, auto-configuration, monitoring, etc., making it suitable for building production-grade applications.

Best Practices​

  1. Error Handling: Use Spring Boot's global exception handling mechanism to uniformly handle exceptions via the @ControllerAdvice annotation.
  2. Response Header Settings: Correctly set the Content-Type and other necessary response headers. You can flexibly control them using Spring's ResponseEntity.
  3. Logging: Use Spring Boot's built-in logging framework (such as SLF4J + Logback) to record key information, facilitating debugging and monitoring.
  4. Code Structure: Leverage Spring Boot annotations to simplify development, such as @RestController, @GetMapping, @PostMapping, etc.
  5. Dependency Management: Use Maven to manage project dependencies and maintain consistency of dependency versions.
  6. Configuration Management: Place configuration information in application.yml or application.properties to support configuration for different environments.
  7. Performance Optimization: Use Spring Boot features like lazy initialization and excluding auto-configuration to optimize startup time.

Next steps​