﻿---
title: API/Code
description: Use the span API to manually create spans for methods of interest. The API is extremely flexible, and offers the ability to customize your spans, by adding...
url: https://www.elastic.co/elastic/docs-builder/docs/3028/reference/apm/agents/java/method-api
products:
  - APM Agent
  - APM Java Agent
applies_to:
  - Serverless Observability projects: Generally available
  - Elastic Stack: Generally available
  - Application Performance Monitoring Agent for Java: Generally available
---

# API/Code
Use the [span API](/elastic/docs-builder/docs/3028/reference/apm/agents/java/public-api#api-span) to manually create spans for methods of interest. The API is extremely flexible, and offers the ability to customize your spans, by adding labels to them, or by changing the type, name, or timestamp.
<tip>
  OpenTracing fan? You can use the [OpenTracing API](https://www.elastic.co/elastic/docs-builder/docs/3028/reference/apm/agents/java/opentracing-bridge), instead of the Agent API, to manually create spans.
</tip>


## How to create spans with the span API

1. Get the current span with [`currentSpan()`](/elastic/docs-builder/docs/3028/reference/apm/agents/java/public-api#api-current-span), which may or may not have been created with auto-instrumentation.
2. Create a child span with [`startSpan()`](/elastic/docs-builder/docs/3028/reference/apm/agents/java/public-api#api-span-start-span).
3. Activate the span with [`activate()`](/elastic/docs-builder/docs/3028/reference/apm/agents/java/public-api#api-span-activate).
4. Customize the span with the [span API](/elastic/docs-builder/docs/3028/reference/apm/agents/java/public-api#api-span).

```java
import co.elastic.apm.api.ElasticApm;
import co.elastic.apm.api.Span;

Span parent = ElasticApm.currentSpan(); 
Span span = parent.startSpan(); 
try (Scope scope = span.activate()) { 
    span.setName("SELECT FROM customer"); 
    span.addLabel("foo", "bar"); 
    // do your thing...
} catch (Exception e) {
    span.captureException(e);
    throw e;
} finally {
    span.end();
}
```


## Combine with annotations

You can combine annotations with the span API to increase their flexibility. Just get the current span on an annotated method and customize the span to your liking.
```java
@CaptureSpan 
private static void spanWithAnnotation(String foo) {
    Span span = ElasticApm.currentSpan(); 
    span.setTag("foo", foo); 
}
```