8000 GitHub - rocketraman/bootable · GitHub
[go: up one dir, main page]

Skip to content
rocketramanPublic

About

No description, website, or topics provided.

Resources

Stars

8 stars

Watchers

1 watching

Forks

Latest commit

 

History

216 Commits

Folders and files

10BC8
NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Bootable

Maven Central GitHub license

A simple, unopinionated framework for booting applications. Intended to be much simpler than Spring Boot or even modern iterations like Quarkus and Micronaut, but still featureful enough to be useful. Handles stopping, starting, lifecycle management, logging, configuration, and other basic reusable components.

Bootable’s core is plain Kotlin and embeds no dependency-injection framework. Its runtime takes two sets — your application services and your lifecycle controllers — and runs them; how you assemble those sets is entirely your choice. Wire them by hand, use a DI solution provided by Bootable as optional add-on artifacts, or bring your own DI. Bootable ships optional bindings for Kodein-DI (clean DSL syntax but executes at runtime) and Metro (complex annotation-based syntax, but executes and checks for a valid dependency graph at compile-time). These are selectable per module, and you can just as easily integrate with any other DI, or none at all.

Why Not Spring Boot?

An important element of simplicity is to prefer the use of explicit references and configuration. Spring Boot’s runtime discovery and configuration of components and plugins via annotation and reflection is easy but not simple. To use Spring Boot, you have to understand two layers: the libraries underneath Spring, as well as all of Spring Boot’s own auto-magic annotations. Many users of Spring Boot fail to understand the hidden complexities, because they never really understand what Spring Boot’s annotations are doing (ever seen @Transactional on a private method — it silently does nothing at all, potentially making that code non-atomic).

Bootable aims to be both easy and simple. The goal of Bootable is to provide a minimal framework for running Kotlin (or Java?) applications, and then gets out of your way.

Useful reading:

Note
Importing the Metro DI artifact does bring annotations to your application, BUT the annotations are limited to the DI layer — the application’s own behavior is not controlled by annotations.

Features

  • Runs a set of application services and lifecycle controllers — assemble them however you like (plain Kotlin, Kodein, Metro, a service loader, …). Bootable embeds no DI framework; optional bindings for Kodein and Metro are available per module. See the examples/ directory for one project per wiring style.

  • Manages the lifecycle of application services.

  • Allows registration of lifecycle controllers, which can be used to control the lifecycle of application services in various ways. The basic built-in implementation of this is the AppStartStopLifecycleController which starts application services on app start, and shuts them down on app close, in reverse. Services start phase by phase (telemetry, infrastructure, initialization, application, serving), and, within a phase, after the milestones they declare; see Service ordering. Services left unordered start by name, or shuffled with boot.service.order.tiebreaker._type = Shuffled in config (or BOOT_SERVICE_ORDER_TIEBREAKER=Shuffled). Shuffling is useful in application-local.conf and test config, to surface services that rely on an order they don’t declare. An app can pass its own StartOrder to add phases; see examples/start-order, which adds a phase after Serving for a service that announces the app is ready once its server is listening. Another basic implementation, intended to be used in conjunction with AppStartStopLifecycleController, is the StopSignalHandlerLifecycleController, which registers signal handlers, which, when received, cleanly shuts the system down. Other implementations are possible: for example starting/stopping services at runtime based on a command system, like start/stop messages from RPCs or web requests.

Modules

Bootable is modular, and provides a number of modules to help you build your application. The core module is simply com.github.rocketraman.bootable:boot, which provides the basic application lifecycle features of Bootable. Add additional modules as you wish.

Configuration

Bootable’s own modules declare a config property that holds a secret, such as a password, an API key, or an auth header, as Masked, from boot-config-common, rather than String. Their config classes don’t depend on a config library, so they can’t use the library’s own type, such as Hoplite’s Secret. Masked has a masked toString, so a config class can be logged or printed safely, and boot-config-hoplite masks it in its config report.

Bootable doesn’t aim to make config libraries interchangeable. In your own config classes, declare secrets with your config library’s type, such as Hoplite’s Secret.

Hoplite

See hoplite.

Add this module to your project to use Hoplite for configuration.

Database (JDBC)

boot-db-jdbc provides a database connection pool tied to the application lifecycle. JdbcDataSourceService validates a connection when the app starts, so an unreachable database fails the boot, and closes the pool on shutdown. It is in the Infrastructure phase, so services that use the database start after it and stop before it.

An application makes two choices, each its own dependency:

  • A driver, which supplies the JdbcConfig: a driver module’s typed config, or the generic JdbcGenericConfig (any database by JDBC URL, with the driver added separately).

    • boot-db-jdbc-sqlite: SqliteConfig takes a file path, and defaults to WAL journaling, enforced foreign keys, a busy timeout, and a single-connection pool.

    • boot-db-jdbc-postgresql: PostgresqlConfig takes a host, port, database, and credentials, plus typed driver settings such as sslMode, currentSchema, and applicationName.

    • boot-db-jdbc-mysql: MysqlConfig takes a host, port, database, and credentials, plus typed driver settings such as sslMode, and defaults to Connector/J’s prepared statement cache.

  • A pool, which supplies the ConnectionPoolFactory, configured with its own typed settings.

    • boot-db-pool-hikari: HikariCP, configured by HikariPoolConfig. For HikariCP settings it doesn’t cover, add a HikariConfigCustomizer to its set binding (Kodein inBindSet, Metro @IntoSet).

On top of the pool, two optional modules use its DataSource:

  • boot-db-flyway: FlywayMigrationService runs Flyway’s migrate when the app starts, just after the pool, so a failed migration fails the boot and nothing uses an unmigrated schema. Migrations come from classpath:db/migration unless FlywayConfig.locations says otherwise. For Flyway settings FlywayConfig doesn’t cover, add a FlywayConfigurationCustomizer to its set binding. flyway-core supports SQLite itself; the PostgreSQL and MySQL driver modules bring their Flyway database modules.

  • boot-db-exposed: ExposedDatabaseService owns an Exposed Database over the pool, configured by ExposedConfig (default isolation level, read-only, retries, query timeout, and so on), which applies to that Database only. On shutdown, before the pool closes, it unregisters the Database from Exposed’s process-wide registry. db.withTransaction { … } runs a suspending transaction on the Database’s dispatcher (`Dispatchers.IO by default); called inside another, it joins it, so several calls make one unit of work. SchemaVerificationService checks, after the migrations, that the schema matches the Exposed tables registered in its Set<Table> binding, and fails the boot listing the SQL the schema needs (or only warns, with schemaVerification = WARN). For Exposed settings ExposedConfig doesn’t cover, add an ExposedConfigCustomizer to its set binding. Exposed logs SQL statements at DEBUG on its Exposed logger.

Each module reads its own subsection of db:

db {
  jdbc {
    path = "./app.db"
  }
  pool {
    connectionTimeout = 5s
  }
  flyway {
    locations = ["classpath:db/migration"]
  }
  exposed {
    defaultMaxAttempts = 1
    schemaVerification = FAIL
  }
}

With vanilla wiring, construct JdbcDataSourceService(binder.config<SqliteConfig>("db.jdbc"), HikariConnectionPoolFactory(binder.config("db.pool"))), pass it to boot as an app service, and hand its dataSource to whatever needs connections: e.g. FlywayMigrationService(dataSource, binder.config("db.flyway")), and an ExposedDatabaseService(dataSource, exposedConfig), as a service too, whose database goes to a SchemaVerificationService for its tables and to your repositories. With Kodein, import jdbcDataSourceModule, a driver config module (sqliteConfigModule, postgresqlConfigModule, mysqlConfigModule, or jdbcGenericConfigModule), and a pool module (hikariPoolModule), plus flywayMigrationModule and exposedDatabaseModule as needed; register tables with inBindSet<Table> { add { singleton { MyTable } } }. With Metro, the -metro driver, pool, Flyway, and Exposed modules contribute everything; for the generic config, add JdbcGenericConfigBindings to your graph’s bindingContainers; register tables with @Provides @IntoSet fun myTable(): Table = MyTable. A graph without a driver or a pool fails to compile with a missing binding.

See examples/server-ktor-db for a small Ktor server that keeps entries in a SQLite database, through a HikariCP pool, with its schema created by a Flyway migration and its queries written with Exposed. Its server code is shared, and it is wired three ways: vanilla, kodein, and metro, each a runnable app, e.g. ./gradlew :examples:server-ktor-db:metro:run.

Environment

Warning
Over-using this abstraction is a code smell.

This module simply exposes a strongly-typed global environment variable to the system, which is initialized from configuration by a lifecycle controller before services start. With vanilla wiring, add environmentInitializer(binder) to the controllers you pass to boot; with Kodein or Metro, this module’s optional bindings provide it for you.

This should be rarely used, but sometimes it is useful to have a way to identify the environment e.g. dev, test, prod, or other. Good use cases are tagging metrics with the environment, or extremely complex environment-specific configuration that can’t be easily abstracted using one of the Configuration modules.

Note that this is also useful in a JavaScript environment, where the environment may be bound to a global variable by something like dotenv-webpack. The environment abstraction may be used to abstract away the underlying details of this binding in a way that can be used in both frontend and backend in the common code source set.

Note
We currently do not publish multi-platform versions of these modules, but may do so in the future.

Logging (Log4j2)

This module provides all the necessary imports to configure Log4j2 as the logging system for the application. It provides good default logging layouts, and supports multiple output types e.g. plain (both color and not), JSON, and GCloud. See LoggingType.

Telemetry (OpenTelemetry)

boot-telemetry-otel provides the application’s OpenTelemetry SDK, for traces and metrics, tied to the application lifecycle. OpenTelemetryService internally manages the OpenTelemetry SDK, so its openTelemetry property can be handed to instrumentation right away, and shuts it down when the application stops, after exporting the spans and metrics still buffered, so the last interval isn’t lost. It is in the Telemetry phase, so every other service, the database pool included, starts after it and stops before it.

  • The resource names the application: serviceName, serviceVersion, and environment (as deployment.environment.name), plus any other resourceAttributes. environment defaults to env.environment, the key boot-env reads, so an application using boot-env gets it without depending on it here. Each instance is told apart by its service.instance.id: serviceInstanceId, where the platform has a stable name for it, such as a pod’s, which the Kubernetes downward API can set as TELEMETRY_SDK_SERVICEINSTANCEID, and otherwise a random one at each start.

  • Traces and metrics are pushed over OTLP (HTTP and protobuf) to otlp.endpoint, such as an OpenTelemetry collector, Jaeger, or Google Cloud; see Push and pull. Without an endpoint there is no OTLP export, so a local run sends nothing anywhere. Each signal can be turned off, or kept off OTLP, and traces.sampleRatio samples traces, keeping a caller’s sampling decision.

  • It records the JVM’s runtime metrics (memory, garbage collection, threads, classes, CPU) unless metrics.runtime is off.

  • Log events within a span carry its trace_id and span_id in their context data, which `boot-logging-log4j2’s layouts print: the plain layouts with the rest of the context, the JSON layout as labels, and the GCloud layout as the fields Cloud Logging links to the trace.

  • Four of the standard OTEL_* environment variables fill in what the config leaves unset; see The standard environment variables.

  • When the OpenTelemetry Java agent is attached, the service uses the agent’s SDK instead of building its own, and leaves its lifecycle to the agent.

Logs aren’t exported over OpenTelemetry for now: the SDK that OpenTelemetryService builds has no logger provider. Logs go through boot-logging-log4j2 as usual, with the trace and span ids above, so a backend can link them to their traces. Ship them with the platform’s log collection, such as Cloud Logging’s, or an OpenTelemetry collector that reads the application’s output.

Tracer.withSpan(name) { span → … } runs a suspending block in a child span of the current one, which stays current across dispatchers, and records an exception as the span’s error. A span from withSpan is expected to have a parent: without one, it starts a trace of its own and logs a warning, once for each span name, since its caller’s trace context usually didn’t reach it, such as across a new CoroutineScope or a Java callback. To start a trace on purpose, such as for a scheduled job or a consumed message, use Tracer.withRootSpan(name) { span → … }, which can also link the trace to the operation that kicked it off. For SDK settings the config doesn’t cover, such as a span processor, a metric view, or another sampler, add an OpenTelemetryCustomizer to its set binding (Kodein inBindSet, Metro @IntoSet); this is also how the modules below plug in. excludeUrlPathsFromTraces(paths) is one, which keeps requests such as health checks out of the traces.

Module Signals Config What it adds

boot-telemetry-otel-prometheus

Metrics

PrometheusTelemetryConfig

Prometheus export: PrometheusTelemetry registers a metric reader with the SDK, and renders the scrape, in the OpenMetrics or Prometheus text format, for an HTTP integration to serve.

boot-telemetry-otel-gcp

Traces, metrics

GcpTelemetryConfig

Google Cloud: the GCP platform’s resource attributes (the Cloud Run service and revision, or the GKE cluster, namespace, and pod), and authentication of OTLP export to Google’s OTLP endpoint, https://telemetry.googleapis.com, which writes traces to Cloud Trace and metrics to Cloud Monitoring, without a collector.

boot-telemetry-otel-signoz

Traces, metrics

SigNozTelemetryConfig

SigNoz, which ingests OTLP itself, at https://ingest.<region>.signoz.cloud:443 for SigNoz Cloud, or a self-hosted SigNoz’s collector on port 4318: the ingestion key on export to SigNoz Cloud, the environment also as deployment.environment, which SigNoz’s filters read, and, optionally, delta temporality for counters and histograms, which SigNoz suggests to cut the samples it stores.

boot-telemetry-otel-micrometer-bridge

Metrics

A Micrometer MeterRegistry that bridges the metrics of libraries that report only to Micrometer, such as the Temporal SDK, to the application’s OpenTelemetry SDK, which exports them with the rest.

boot-server-http-ktor-otel

Traces, metrics

KtorTelemetryConfig

Ktor server instrumentation, and the metrics scrape for a pulling backend; see below.

KtorTelemetry, from boot-server-http-ktor-otel, installs OpenTelemetry’s Ktor instrumentation, which traces every request, continuing the caller’s trace when the request carries one, and records the standard HTTP server metrics, such as http.server.request.duration. It also serves a pulled backend’s scrape at /metrics, and keeps those scrapes out of the traces. Call installTelemetry(telemetry) in your server’s module(); the request’s span is current while its route runs, so withSpan in a route starts a child of it. To keep the scrape off a public server, set telemetry.ktor.hostPort: the scrape is then served on a listener of its own, telemetry.listener(CIO) (or another engine), which you add to the application’s services. Without hostPort, that listener is a service that does nothing, so it can be added either way.

For a library without a Bootable module that instruments it, such as boot-server-http-ktor-otel does Ktor, hand the application’s openTelemetry to the library’s OpenTelemetry instrumentation yourself, where you build its client. For HikariCP’s pool metrics, for example, add io.opentelemetry.instrumentation:opentelemetry-hikaricp-3.0, and give HikariConnectionPoolFactory a HikariConfigCustomizer that sets metricsTrackerFactory = HikariTelemetry.create(openTelemetry).createMetricsTrackerFactory(). examples/server-ktor-db does this, wired each of the three ways.

Each module reads its own subsection of telemetry:

telemetry {
  sdk {
    serviceName = my-service
    otlp { endpoint = "http://otel-collector:4318" }
    traces { sampleRatio = 0.1 }
    metrics { interval = 30s }
  }
  prometheus {
    resourceAttributesAsLabels = [service.name]
  }
  gcp {
    projectId = my-project
  }
  signoz {
    ingestionKey = ${?SIGNOZ_INGESTION_KEY}
  }
  ktor {
    hostPort = ":9090"
  }
}

With vanilla wiring, build the customizers, then an OpenTelemetryService(telemetryConfig(binder), listOf(prometheus, ktorConfig.excludeScrapeFromTraces())), pass it to boot as an app service, and hand its openTelemetry to whatever records telemetry: e.g. KtorTelemetry(telemetry.openTelemetry, setOf(prometheus), ktorConfig). With Kodein, import openTelemetryModule, then prometheusTelemetryModule, gcpTelemetryModule, sigNozTelemetryModule, micrometerBridgeModule, and ktorTelemetryModule as needed, and bind OpenTelemetry and KtorTelemetry where needed. With Metro, the -metro modules contribute everything.

examples/server-ktor-db traces its requests, with a span for each database operation within them, records its request, pool, and runtime metrics and a counter of its own, and serves them at http://localhost:8001/metrics, wired each of the three ways. Its metrics are pulled, so they need nothing else running, but its traces are pushed: to see them, point OTEL_EXPORTER_OTLP_ENDPOINT at an OpenTelemetry collector or Jaeger (see Push and pull). Its README shows how to see both locally, with Grafana or Jaeger in a container.

Push and pull

Telemetry reaches a backend in one of two ways. With push, the application sends it: the SDK exports spans as they finish, and metrics every metrics.interval, over OTLP to otlp.endpoint. With pull, the backend fetches it: a scraper, such as Prometheus or VictoriaMetrics, fetches the application’s /metrics on its own schedule, and the application only keeps each metric’s current value.

Push over OTLP is OpenTelemetry’s own model, and the only supported approach for traces. Metrics can go either way: pushed over OTLP, pulled in the Prometheus format with boot-telemetry-otel-prometheus, or both at once.

Each has its strengths. Pull keeps the application ignorant of where its metrics go, needs no credentials in it, and tells the backend when a target is down, because the scrape fails. Push works where nothing can reach the application to scrape it: short-lived jobs, instances behind NAT, and platforms such as Cloud Run, whose instances have no stable address and stop when idle.

The application usually pushes to an OpenTelemetry collector beside it, such as a sidecar or a node agent, rather than straight to the backend. The collector batches, retries, samples, and holds the backend’s credentials, so the application needs only its address. A collector can also scrape Prometheus endpoints, so the two models mix. Some backends take OTLP directly, without a collector: Jaeger, for one, Google Cloud, with boot-telemetry-otel-gcp, and SigNoz, with boot-telemetry-otel-signoz.

Recommendations that work for most cases:

  • With a pulling backend, such as Prometheus, already in place, let it pull the metrics, and push the traces over OTLP.

  • With a collector, or a hosted backend, push both over OTLP, and leave Prometheus out.

  • Locally, nothing needs to be running: without an endpoint nothing is pushed, and the metrics can still be pulled.

The standard environment variables

OpenTelemetry defines environment variables that platforms and tools set, such as the OpenTelemetry operator for Kubernetes, and that other OpenTelemetry SDKs read. Settings are configured explicitly in telemetry.sdk, which telemetryConfig decodes, and Bootable falls back to four of the standard variables for the settings not explicitly configured:

Variable Explicit configuration When both are set

OTEL_SERVICE_NAME

serviceName

The explicit serviceName wins. OTEL_SERVICE_NAME wins over a service.name in resourceAttributes, as it does in other SDKs.

OTEL_RESOURCE_ATTRIBUTES

resourceAttributes

Merged by key; the explicit value wins for a key in both.

OTEL_EXPORTER_OTLP_ENDPOINT

otlp.endpoint

The explicit endpoint wins.

OTEL_EXPORTER_OTLP_HEADERS

otlp.headers

Merged by header name; the explicit value wins for a header in both.

The variables take their standard format, described in OpenTelemetry’s SDK environment variables and OTLP exporter specifications. Explicit configuration comes from any of Hoplite’s sources, so a TELEMETRY_SDK_* environment variable, such as TELEMETRY_SDK_SERVICENAME, is explicit too, and wins over the matching OTEL_* one. The values end up in the TelemetryConfig that telemetryConfig returns, with the headers Masked, but not in Hoplite’s config report, which only lists what Hoplite decoded.

If you build a TelemetryConfig in code instead of with telemetryConfig, such as in a test, the variables are ignored, so it doesn’t depend on the environment it runs in. To apply them to it, call withOtelEnvironment() on it. No other OTEL_* variable is read, such as OTEL_TRACES_SAMPLER or OTEL_METRIC_EXPORT_INTERVAL: set the matching config instead, which a HOCON substitution can take from any environment variable, e.g. sampleRatio = ${?TRACES_SAMPLE_RATIO}.

Server HTTP (Ktor)

Provides a basic Ktor service abstraction with Bootable lifecycle integration i.e. the server starts and stops with the application. Does not attempt to configure Ktor in any significant way — this is left to the user. To trace and measure requests, and serve a metrics scrape, see boot-server-http-ktor-otel under Telemetry (OpenTelemetry). See KtorService.

The Ktor engine is your choice. boot-server-http-ktor itself depends on no engine; depend on the module for the engine you want, which brings that engine with it, and extend its service class:

Module Extend Engine

boot-server-http-ktor-cio

CioKtorService

CIO: pure Kotlin, and the engine to use for a GraalVM native image

boot-server-http-ktor-netty

NettyKtorService

Netty

boot-server-http-ktor-jetty

JettyKtorService

Jetty 12 (ktor-server-jetty-jakarta)

class MyServer(config: ServerConfig) : CioKtorService("my-server", config) {
  override fun Application.module() {
    routing { get("/") { call.respondText("hello") } }
  }
}

Any other engine works too: depend on boot-server-http-ktor and that engine, and extend KtorService with the engine’s factory, e.g. KtorService<MyEngine, MyEngine.Configuration>("my-server", config, MyEngine).

Every engine is configured the same way: one connector at the service’s HostPort (port 8080 if it has none), a 50 ms shutdown grace period, and a 1 s shutdown timeout. To change those, add connectors, or set the engine’s own options, override configureEngine, whose receiver is the engine’s configuration type:

override fun NettyApplicationEngine.Configuration.configureEngine() {
  shutdownTimeout = 5_000
  responseWriteTimeoutSeconds = 30
}
Note
Before 3.1, KtorService always ran on Netty, and boot-server-http-ktor brought Netty with it. To upgrade, depend on boot-server-http-ktor-netty instead of boot-server-http-ktor, and extend NettyKtorService instead of KtorService; nothing else changes.

See examples/compose-html for a Kotlin web application end to end: a todo list whose browser client is written with Compose HTML, served by a Ktor server run by Bootable. The API’s models and validation rule live in a multiplatform shared module, compiled to JavaScript for the client and to the JVM for the server, so both sides agree on the JSON and on what makes a todo valid. The server’s build bundles the client’s production JavaScript onto its classpath, so ./gradlew :examples:compose-html:server:run serves the whole app at http://localhost:8002. To work on the client with live reload, run the server too, and ./gradlew :examples:compose-html:client:jsBrowserDevelopmentRun, whose development server forwards API calls to it.

See examples/htmx for the same todo list rendered on the server instead: pages built with kotlinx.html, and made interactive with htmx, using Ktor’s HTMX support. It runs with ./gradlew :examples:htmx:run, at http://localhost:8003.

See examples/kilua for the same todo list written with Kilua, a Compose-based alternative to Compose HTML, and also rendered on the server, by running the client in Node.js, in a process that Bootable starts before the server. It runs with ./gradlew :examples:kilua:server:run, at http://localhost:8004, with the Node.js that Gradle downloads.

How to Use

See Wiring Bootable for the full guide, and the projects in the examples directory — there is one per wiring style, so you can copy the one that matches your choice of DI (or no DI).

The essentials, regardless of wiring:

  • Application components that have a lifecycle implement AppService or AdvancedAppService.

  • You assemble a Set<AppService> and a Set<LifecycleController>, and hand them to the boot function, which runs them. With vanilla wiring that is just boot { Bootable(setOf(MyService(…​))) } — lifecycleControllers defaults to defaultLifecycleControllers().

  • defaultLifecycleControllers() provides the built-in start/stop and signal-handling controllers. To run a custom lifecycle — e.g. starting/stopping services on command from an RPC or web request rather than at boot — pass your own controllers instead.

To use a DI framework, depend on the -kodein or -metro artifact of each module you use (e.g. boot-kodein, boot-config-hoplite-kodein, boot-env-kodein, or the -metro equivalents) and let it assemble the sets:

  • Kodein (runtime): import the provided bootableModule / hopliteConfigModule / environmentModule, contribute your services with bindAppService { … }, and pass the resolved sets to boot.

  • Metro (compile-time): declare a @DependencyGraph that extends BootableGraph, contribute your services with @ContributesIntoSet, and boot { createGraph<AppGraph>().bootable }.

Design

Non-Goals

Bootable provides useful capabilities on top of well-chosen libraries, not an abstraction over them.

  • Interchangeable libraries. Bootable doesn’t aim to make the libraries it builds on, such as Hoplite for configuration, or Exposed and HikariCP for databases, interchangeable with others. Use their types and APIs directly: Bootable exposes them rather than wrapping them. That includes dependency injection: Bootable provides bindings for Kodein and Metro, not an abstraction over them, and an application uses its chosen DI directly.

  • Every feature of every library. Bootable’s modules set up the common case. For anything more, configure the library itself, through the hooks a module provides, such as HikariConfigCustomizer, ExposedConfigCustomizer, or hopliteConfigBinder's parameters.

  • Requiring Bootable’s modules. Use Bootable’s modules, or integrate the library directly, or use a different library if it fits your use case better. Bootable’s core is just application lifecycle management.

This philosophy is quite different from Spring Boot’s, which attempts to abstract away libraries with common Spring Boot factories and APIs. Users then have to understand two abstractions: the library’s own, as well as Spring Boot’s. It makes leveraging each library’s unique capabilities more difficult than necessary. These capabilities are either unavailable or only exposed via a complex set of ostensibly library-independent customizers and injectors. Swapping in your own component is difficult — other components of Spring Boot assume you are using and configuring their abstraction.

Dependency Injection

Everyone has their own preferences: no DI at all, relying solely on constructor injection and context parameters, compile-time annotation-based frameworks like Metro, Dagger or kotlin-inject, or runtime DSL based options like Kodein and Koin. We don’t want to impose a choice on users. Bootable is designed to be DI independent — combine it with whichever DI you like, or no DI at all.

That being said, Bootable ships with bindings for two popular options: Metro and Kodein. Simply pull in the -metro or -kodein suffixed variants of each module to use them.

Which DI Should I Use?

The heavy-weight nature of DI frameworks like Spring has given DI a bit of a bad rap, and many people argue it is unnecessary in Kotlin — that constructor injection and context parameters are enough. This is absolutely true for small projects, but as a project grows the need for modularity arises: consider a multi-module app, each module of which exposes one or more AppService implementations without any central code being aware of them all. Collecting those into a Set<AppService> is exactly what a DI container’s multibindings do well — but it is also easy to do by hand, and different teams reasonably prefer different approaches.

We recommend most teams use Metro, which provides a strong feature-set with compile-time graph construction and validation via a set of DI-specific annotations.

Note
Unlike Spring, these annotations do not control or configure framework or application behavior. They simply manage the dependency graph.

With Metro, missing dependencies or other dependency issues are a compile error, not a runtime error. Also, while startup time differences are usually minimal, applications with large graphs will benefit from compile-time graph construction, which at runtime will have construction performance rivaling vanilla no-DI setups.

If a clean simple DSL is important to you, then consider Kodein. Compared to Metro, it has no compile-time graph checking, and is slightly slower to initialize on application startup since it wires the graph at runtime via reflection. But it is straightforward to use and produces readable DI module definitions.

See these three wiring options for example code:

How Do I Integrate Random DI with Bootable?

Bootable’s core is plain Kotlin: the AppService / LifecycleController interfaces, the built-in controllers, and the main framework class Bootable.kt carry no DI annotations, and Bootable takes its two sets through an ordinary constructor. The seam is those two sets; how you fill them is up to you.

For convenience, each module that has anything to wire ships optional Kodein and Metro bindings as separate -kodein / -metro artifacts (e.g. boot-metro), each depending on the plain module, so you can opt into a batteries included DI framework by simply importing the selected dependencies with the suffix for the chosen DI.

TODOs

  • ❏ Multiple logging implementations for different scenarios, loggingInit via ServiceLoader?

  • ❏ Create a boot-server-http-ktor-cohort module using Cohort

  • ❏ Update the ktor example to integrate Kompendium — this is outside the scope of Bootable, but it would be a good example of how to integrate Bootable with other libraries

  • ❏ Make multiplatform — some modules are backend only e.g. Hoplite, Log4j2, but others could easily be adapted for multiplatform usage

  • ❏ Integrate more useful modules

Author

Raman Gupta <rocketraman@gmail.com>

About

No description, website, or topics provided.

Resources

Stars

8 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

0