Skip to content
FlagSwiftDocs

Java SDK

A builder client and a Spring Boot 3 starter.

Compare SDKs

Use this SDK in Java services and Spring Boot applications. It downloads your environment's configuration, keeps it fresh and evaluates every flag in memory, so a check never touches the network. For other backends see the .NET, Go and Node.js SDKs. Options and behaviour every SDK shares are on Options and behaviour.

At a glance#

Install
Maven: io.flagswift:flagswift-java
Requires
Java 11+ (the Spring Boot starter needs Java 17)
Key
Server key (fs_srv_)
Evaluates
Locally, in memory
Real-time updates
Yes
Works offline from
Snapshot file
Outcome analytics
Yes
Verified
javac and JUnit only, no real Maven build

Options, user context and behaviour every SDK shares are on Options and behaviour. To compare SDKs, see SDK features.

Installation#

xml
<dependency>
  <groupId>io.flagswift</groupId>
  <artifactId>flagswift-java</artifactId>
  <version>1.0.0</version>
</dependency>

The SDK needs Java 11 or newer. Its only runtime dependency is jackson-databind, and HTTP uses the JDK's java.net.http.HttpClient. The Spring Boot starter needs Java 17 and Spring Boot 3.

Placeholder coordinates

The group id io.flagswift is a placeholder until the publishing location is decided, and nothing is published yet. Build from the repository (mvn install in sdks/java) for now.

Initialization#

You need a server key (fs_srv_…) or admin key with the evaluation:read scope, and the address of your FlagSwift server. There is no default host. Keep the key on the server. In a long-lived application create one client, call initialize() at startup and close() at shutdown. The client implements AutoCloseable.

Checkout.java
import io.flagswift.*;
import java.nio.file.Path;
import java.time.Duration;

try (FlagSwift flags = FlagSwift.builder()
        .apiKey(System.getenv("FLAGSWIFT_KEY"))     // a server key (fs_srv_) or admin key
        .baseUrl("https://flags.example.com")       // your FlagSwift server; no default
        .environment("production")                  // only for project-wide keys
        .fallback("new-checkout", false)
        .refreshInterval(Duration.ofSeconds(30))
        .snapshotPath(Path.of("/var/cache/myapp/flagswift.json"))
        .onError(e -> log.warn("flagswift: {}", e.toString()))
        .build()) {

    flags.initialize();   // waits at most 5 s for the first fetch; never throws

    // ... use flags
}

Startup never blocks for long

initialize() returns true when a configuration is loaded and false otherwise, and it never throws. The fetch and the poller carry on on daemon threads and apply the configuration as soon as one succeeds, so the SDK never keeps your JVM alive.

Connection options#

apiKey and baseUrl are required. Everything else has a default.

Common options of FlagSwift.builder()
OptionTypeDescription
apiKey(String), baseUrl(String)*StringA server or admin key and your server address (http:// or https://).
environment(String)StringOnly for project-wide keys. Defaults to the FLAGSWIFT_ENVIRONMENT variable.
refreshInterval(Duration)DurationHow often to check for changes. Default 30 seconds. Zero or negative turns polling off.
streaming(boolean)booleanReal-time updates over Server-Sent Events. Default false.
fallback(key, value), fallbacks(Map)ObjectServed for unknown flags and before anything loads. A Boolean answers isEnabled; anything else answers getValue.
snapshotPath(Path)PathFile that keeps the last configuration across restarts (atomic write, owner-only).
bootstrap(String or Map)String | MapStart from a saved configuration, so evaluation works before and without the network.
timeout, initTimeoutDurationPer request and the longest initialize() waits. Default 5 seconds each.
maxRetries(int)intDefault 3. Zero disables retries.
autoExposures(boolean)booleanQueue an exposure on every single-flag read. Default false.
onError, onUpdateConsumerCallbacks. They run on SDK threads, so keep them quick and thread-safe.
httpClient(HttpClient)HttpClientYour own client, for proxies or TLS.

Check flags#

Build a FlagUser to say who is asking. isEnabled returns the configured fallback (default false) for a flag the server does not know. A three-argument form takes your own default.

java
FlagUser user = FlagUser.builder()
        .identifier("user-42")
        .account("acme")
        .attribute("plan", "pro")
        .build();

if (flags.isEnabled("new-checkout", user)) {
    renderNewCheckout();
}

// Your own default when the flag is not found.
boolean beta = flags.isEnabled("beta-banner", user, true);

// The reason behind an answer.
Evaluation ev = flags.evaluate("new-checkout", user);
log.info("enabled={} reason={} found={}", ev.isEnabled(), ev.getReason(), ev.isFound());

Check variants and values#

A flag can serve a named variant, such as a button colour or a plan limit. getVariant gives its key as an Optional, and getValue gives what it carries, typed if you pass a class.

java
Optional<String> variant = flags.getVariant("checkout-layout", user);   // "compact", "wide" or empty
Object value = flags.getValue("seat-limit", user, 5);
Integer limit = flags.getValue("seat-limit", user, 5, Integer.class);    // typed

Map<String, Evaluation> all = flags.evaluateAll(user);                  // every loaded flag

Describe the person#

FlagUser.builder() takes identifier(s), account(s), device(s) and attribute(key, value). Rollouts bucket on the first identifier, and any identifier can match explicit targeting. FlagUser.of("id") is a shorthand for one identifier. A FlagUser is immutable and safe to share. Attributes feed targeting rules and never leave your server.

Spring Boot#

The starter creates the FlagSwift bean from application.yml, closes it on shutdown and adds an annotation for controllers. The application always boots: startup waits at most init-timeout, then serves fallbacks or the saved snapshot while the client keeps retrying with backoff.

application.yml
flagswift:
  api-key: ${FLAGSWIFT_API_KEY}      # a server key (fs_srv_...)
  base-url: https://flags.example.com
  environment: production            # only for project-wide keys
  streaming: true                    # optional real-time updates
  fallbacks:
    new-checkout: false

Inject the client anywhere, and guard a route with @FeatureFlag. When the flag is off for the caller, the route answers 404, or 403 with flagswift.disabled-status: 403.

java
@Service
class Checkout {
    private final FlagSwift flags;
    Checkout(FlagSwift flags) { this.flags = flags; }

    boolean useNewFlow(String userId) {
        return flags.isEnabled("new-checkout", FlagUser.of(userId));
    }
}

@RestController
class ReportsController {
    @FeatureFlag("beta-reports")
    @GetMapping("/reports/beta")
    String beta() { return "..."; }
}

Who is the person?#

By default the starter uses the authenticated principal's name, then the X-User-Id header, otherwise an anonymous user. Define a FlagUserResolver bean to add accounts, devices or attributes for targeting.

java
@Bean
FlagUserResolver flagUserResolver() {
    return request -> FlagUser.builder()
            .identifier(request.getHeader("X-User-Id"))
            .account(request.getHeader("X-Tenant"))
            .attribute("plan", request.getHeader("X-Plan"))
            .build();
}

Other starter settings are refresh-interval, timeout, init-timeout, streaming-poll-interval, auto-exposures, snapshot-path, disabled-status, user-header (X-User-Id) and enabled.

Hibernate and JPA

There is no separate Hibernate package: flags are decisions in your code, not data access. Check a flag before choosing a query or a code path, the same way as anywhere else.

Real-time updates#

By default the client polls. With streaming on, a flag change reaches your service in about a second. The stream carries only a note that something changed, never flag data, and the client then refetches with its normal conditional request.

java
FlagSwift flags = FlagSwift.builder().apiKey(key).baseUrl(url).streaming(true).build();

While the stream is connected, polling slows to streamingPollInterval (default 5 minutes) as a safety net, never shorter than refreshInterval. If streaming is off on the server or cannot be kept, polling carries on alone. status().getStreaming() reports OFF, CONNECTING, CONNECTED or UNAVAILABLE.

Offline and errors#

Once a configuration has loaded, from the server, a snapshot or a bootstrap, evaluation is purely local. It keeps working with no internet and through a FlagSwift outage, and it never throws.

What happens when something goes wrong
SituationDescription
A refresh failsThe last good configuration and its ETag stay. The failure is recorded in status() and passed to onError, and polling backs off up to five minutes. The next success resets it.
First load, nothing storedYou get your fallbacks, then false, until the response arrives. initialize() waits at most initTimeout.
Restart during an outageWith snapshotPath the saved file is served from build(). A corrupt file, or one from another hashVersion, is ignored.
Bootstrap from your own storageSave flags.getSnapshot() and pass it to bootstrap(...).
Explicit refreshrefresh() throws FlagSwiftException on failure and keeps the last good configuration. It is the only call that throws.
Reading the statestatus() has getLastError(), getErrorCount(), getConsecutiveFailures(), getFlagCount() and getLastFetchTime().

Outcome analytics#

Report what people saw and what they did so FlagSwift can compare variants. Nothing is sent unless you call these or turn autoExposures on, and only the person's identifier, the flag, the variant and the event name leave your service.

java
flags.trackExposure("checkout-flow", user);   // evaluates locally, queues the outcome this person got
flags.track("purchase", user, 49.90);         // what they did; the value is optional
flags.flushAnalytics();                       // send what is queued now and wait

close() flushes what is left on a best-effort basis. See Outcomes for how results are read in the console.

Reference#

Package io.flagswift:flagswift-java (version 1.0.0, Java 11 or later) and an optional Spring Boot 3 starter, flagswift-spring-boot-starter (Java 17). Build a client with FlagSwift.builder(), call initialize() once at startup and close() at shutdown. It implements AutoCloseable and is safe to share between threads.

Builder options
OptionDescription
apiKey(String), baseUrl(String)Required. A server (fs_srv_) or admin key with the evaluation:read scope, and your server address. There is no default host.
environment(String)Only for project-wide keys. Defaults to the FLAGSWIFT_ENVIRONMENT variable.
refreshInterval(Duration), timeout(Duration), initTimeout(Duration), maxRetries(int)30 seconds, 5 seconds, 5 seconds and 3 retries. A zero or negative refresh interval turns polling off.
fallback(key, value), fallbacks(Map)Served for an unknown flag or before anything has loaded. A Boolean answers isEnabled; anything else answers getValue.
bootstrap(String or Map), snapshotPath(Path)Start from a saved configuration, or keep the last one in a file (atomic write, owner-only) so a restart works while the server is down.
streaming(boolean), streamingPollInterval(Duration)Real-time updates over Server-Sent Events (default off), and the slower poll used while connected (5 minutes).
autoExposures(boolean)Queue an exposure on every single-flag read that finds a flag. Default false.
reportErrors(boolean), onError(Consumer), onUpdate(Consumer), httpClient(HttpClient)Error-count reporting (default true), callbacks that must not block, and your own HTTP client for proxies or TLS.
Methods
MethodDescription
initialize()Fetches, starts polling and the stream. Returns true when a configuration is loaded. Never throws.
refresh()Fetches now. Throws FlagSwiftException on failure; the last good configuration stays.
isEnabled(flag, user[, fallback])Is the flag on. Unknown flag: the configured fallback (default false).
getVariant(flag, user) / getValue(flag, user, fallback[, Class])The variant key as an Optional, or the variant's value (typed with a Class).
evaluate(flag, user) / evaluateAll(user)An Evaluation (isEnabled, getVariant, getValue, getReason, isFound), or every loaded flag for one person. evaluateAll does not report exposures.
trackExposure(flag, user) / track(event, user[, value]) / flushAnalytics()Outcome analytics. Evaluation is local, queues the outcome this person got, and never throws.
getFlagKeys(), getSnapshot(), getSnapshotMap(), status()Known keys, the loaded configuration for bootstrap, and a status with initialization, version, errors, streaming and analytics (pending, sent, dropped, enabled).
close() / destroy()Stops polling and the stream and flushes analytics. Idempotent.
Spring Boot starter
PieceDescription
flagswift.* in application.ymlapi-key, base-url, environment, streaming, fallbacks, refresh-interval, timeout, init-timeout, streaming-poll-interval, auto-exposures, snapshot-path and disabled-status.
FlagSwift beanCreated from the settings and closed on shutdown. The application always boots: startup waits at most init-timeout, then serves fallbacks or the saved snapshot.
@FeatureFlag("name")On a controller method. The route answers 404 (or 403 with flagswift.disabled-status) when the flag is off for the caller.

Not yet published or fully built

The coordinates are placeholders until a publishing location is decided. The SDK was compiled and tested with javac and JUnit against Jackson, but not with a real Maven build, and the Spring Boot starter was only compiled against stand-ins for Spring. Treat both as unverified until you run their tests.