0
# Java Interoperability
1
2
Java-specific API for dependency injection in mixed Kotlin/Java projects with static access patterns. Enables seamless integration of Koin dependency injection in Java codebases and Java-Kotlin interop scenarios.
3
4
## Capabilities
5
6
### KoinJavaComponent
7
8
Static access point for dependency injection in Java code with full feature parity to Kotlin APIs.
9
10
```kotlin { .api }
11
/**
12
* Java-compatible component providing static access to Koin functionality
13
*/
14
object KoinJavaComponent {
15
/**
16
* Inject dependency lazily in Java code
17
* @param clazz - Class type to inject
18
* @param qualifier - Optional qualifier for disambiguation
19
* @param parameters - Optional parameters for injection
20
* @return Lazy instance of the requested type
21
*/
22
@JvmStatic
23
@JvmOverloads
24
fun <T> inject(
25
clazz: Class<*>,
26
qualifier: Qualifier? = null,
27
parameters: ParametersDefinition? = null
28
): Lazy<T>
29
30
/**
31
* Inject dependency lazily with null safety in Java code
32
* @param clazz - Class type to inject
33
* @param qualifier - Optional qualifier for disambiguation
34
* @param parameters - Optional parameters for injection
35
* @return Lazy instance of the requested type or null
36
*/
37
@JvmStatic
38
@JvmOverloads
39
fun <T> injectOrNull(
40
clazz: Class<*>,
41
qualifier: Qualifier? = null,
42
parameters: ParametersDefinition? = null
43
): Lazy<T?>
44
45
/**
46
* Get dependency instance immediately in Java code
47
* @param clazz - Class type to get
48
* @param qualifier - Optional qualifier for disambiguation
49
* @param parameters - Optional parameters for injection
50
* @return Instance of the requested type
51
*/
52
@JvmStatic
53
@JvmOverloads
54
fun <T> get(
55
clazz: Class<*>,
56
qualifier: Qualifier? = null,
57
parameters: ParametersDefinition? = null
58
): T
59
60
/**
61
* Get dependency instance with null safety in Java code
62
* @param clazz - Class type to get
63
* @param qualifier - Optional qualifier for disambiguation
64
* @param parameters - Optional parameters for injection
65
* @return Instance of the requested type or null
66
*/
67
@JvmStatic
68
@JvmOverloads
69
fun <T> getOrNull(
70
clazz: Class<*>,
71
qualifier: Qualifier? = null,
72
parameters: ParametersDefinition? = null
73
): T?
74
75
/**
76
* Get the global Koin instance
77
* @return Global Koin instance
78
*/
79
@JvmStatic
80
fun getKoin(): Koin
81
}
82
```
83
84
**Usage Examples:**
85
86
**Java Code:**
87
88
```java
89
import org.koin.java.KoinJavaComponent;
90
import org.koin.core.qualifier.Qualifier;
91
import org.koin.core.parameter.ParametersDefinition;
92
93
// Basic injection in Java
94
public class UserController {
95
// Lazy injection - resolved on first access
96
private final Lazy<UserService> userService =
97
KoinJavaComponent.inject(UserService.class);
98
99
// Direct injection - resolved immediately
100
private final Logger logger =
101
KoinJavaComponent.get(Logger.class);
102
103
public User createUser(UserData userData) {
104
logger.info("Creating user");
105
return userService.getValue().create(userData);
106
}
107
}
108
109
// Injection with qualifiers
110
public class PaymentService {
111
private final Lazy<PaymentGateway> primaryGateway =
112
KoinJavaComponent.inject(
113
PaymentGateway.class,
114
KoinKt.named("primary")
115
);
116
117
private final PaymentGateway backupGateway =
118
KoinJavaComponent.getOrNull(
119
PaymentGateway.class,
120
KoinKt.named("backup")
121
);
122
123
public boolean processPayment(Payment payment) {
124
try {
125
return primaryGateway.getValue().process(payment);
126
} catch (Exception e) {
127
if (backupGateway != null) {
128
return backupGateway.process(payment);
129
}
130
throw e;
131
}
132
}
133
}
134
135
// Injection with parameters
136
public class ReportGenerator {
137
public Report generateReport(String reportType, Date fromDate, Date toDate) {
138
ParametersDefinition params = () -> ParametersKt.parametersOf(
139
reportType, fromDate, toDate
140
);
141
142
ReportBuilder builder = KoinJavaComponent.get(
143
ReportBuilder.class,
144
null,
145
params
146
);
147
148
return builder.build();
149
}
150
}
151
152
// Advanced usage with Koin instance
153
public class DatabaseManager {
154
private final Koin koin = KoinJavaComponent.getKoin();
155
156
public void switchDatabase(String environment) {
157
// Use Koin instance directly for advanced operations
158
DatabaseConfig config = koin.get(
159
DatabaseConfig.class,
160
KoinKt.named(environment),
161
null
162
);
163
164
// Reconfigure database connection
165
reconfigure(config);
166
}
167
}
168
```
169
170
**Mixed Java/Kotlin Usage:**
171
172
```kotlin
173
// Kotlin module definition
174
val javaInteropModule = module {
175
single<UserService> { UserServiceImpl(get()) }
176
single<Logger> { LoggerImpl() }
177
178
single<PaymentGateway>(named("primary")) { StripePaymentGateway() }
179
single<PaymentGateway>(named("backup")) { PayPalPaymentGateway() }
180
181
factory<ReportBuilder> { (type: String, from: Date, to: Date) ->
182
ReportBuilderImpl(type, from, to)
183
}
184
185
single<DatabaseConfig>(named("production")) { ProductionDbConfig() }
186
single<DatabaseConfig>(named("development")) { DevelopmentDbConfig() }
187
}
188
189
// Start Koin with Java-compatible setup
190
startKoin {
191
modules(javaInteropModule)
192
}
193
```
194
195
```java
196
// Java classes using the Kotlin-defined dependencies
197
public class Application {
198
public static void main(String[] args) {
199
// Dependencies are available via KoinJavaComponent
200
UserController controller = new UserController();
201
PaymentService paymentService = new PaymentService();
202
203
// Use the services
204
User user = controller.createUser(new UserData("John", "john@example.com"));
205
boolean success = paymentService.processPayment(new Payment(100.0));
206
}
207
}
208
```
209
210
### Integration Patterns
211
212
Common patterns for integrating Koin in Java applications and frameworks.
213
214
**Usage Examples:**
215
216
**Servlet Integration:**
217
218
```java
219
import javax.servlet.ServletContext;
220
import javax.servlet.ServletContextEvent;
221
import javax.servlet.ServletContextListener;
222
223
public class KoinServletListener implements ServletContextListener {
224
@Override
225
public void contextInitialized(ServletContextEvent sce) {
226
// Initialize Koin when servlet context starts
227
ServletContext context = sce.getServletContext();
228
229
// Start Koin with configuration
230
KoinApplication app = StartKoinKt.startKoin(koinApp -> {
231
koinApp.modules(WebModulesKt.getWebModules());
232
return null;
233
});
234
235
// Store Koin instance in servlet context
236
context.setAttribute("koin", app.getKoin());
237
}
238
239
@Override
240
public void contextDestroyed(ServletContextEvent sce) {
241
// Clean up Koin when servlet context stops
242
StopKoinKt.stopKoin();
243
}
244
}
245
246
// Servlet using Koin
247
public class UserServlet extends HttpServlet {
248
private final Lazy<UserService> userService =
249
KoinJavaComponent.inject(UserService.class);
250
251
@Override
252
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
253
String userId = req.getParameter("userId");
254
User user = userService.getValue().findById(userId);
255
256
// Handle response
257
resp.getWriter().write(user.toJson());
258
}
259
}
260
```
261
262
**Spring Integration:**
263
264
```java
265
import org.springframework.context.annotation.Bean;
266
import org.springframework.context.annotation.Configuration;
267
268
@Configuration
269
public class KoinSpringBridge {
270
271
// Expose Koin dependencies as Spring beans
272
@Bean
273
public UserService userService() {
274
return KoinJavaComponent.get(UserService.class);
275
}
276
277
@Bean
278
public PaymentProcessor paymentProcessor() {
279
return KoinJavaComponent.get(PaymentProcessor.class);
280
}
281
282
// Initialize Koin alongside Spring
283
@Bean
284
public KoinApplication koinApplication() {
285
return StartKoinKt.startKoin(app -> {
286
app.modules(ApplicationModulesKt.getAppModules());
287
return null;
288
});
289
}
290
}
291
```
292
293
**JUnit Test Integration:**
294
295
```java
296
import org.junit.jupiter.api.BeforeEach;
297
import org.junit.jupiter.api.AfterEach;
298
import org.junit.jupiter.api.Test;
299
300
public class ServiceTest {
301
302
@BeforeEach
303
void setUp() {
304
// Start Koin for testing
305
StartKoinKt.startKoin(app -> {
306
app.modules(TestModulesKt.getTestModules());
307
return null;
308
});
309
}
310
311
@AfterEach
312
void tearDown() {
313
// Clean up after each test
314
StopKoinKt.stopKoin();
315
}
316
317
@Test
318
void testUserService() {
319
UserService userService = KoinJavaComponent.get(UserService.class);
320
321
User user = userService.create(new UserData("Test User"));
322
assertNotNull(user);
323
assertEquals("Test User", user.getName());
324
}
325
326
@Test
327
void testPaymentServiceWithQualifier() {
328
PaymentGateway gateway = KoinJavaComponent.get(
329
PaymentGateway.class,
330
KoinKt.named("test")
331
);
332
333
assertTrue(gateway instanceof MockPaymentGateway);
334
}
335
}
336
```
337
338
## Types
339
340
### Java-Compatible Types
341
342
```kotlin { .api }
343
// All standard Koin types are available in Java through static imports
344
// Qualifiers
345
val named: (String) -> Qualifier = ::named
346
val qualifier: (String) -> Qualifier = ::qualifier
347
348
// Parameters
349
val parametersOf: (Array<Any>) -> ParametersHolder = ::parametersOf
350
351
// Type aliases for Java compatibility
352
typealias ParametersDefinition = () -> ParametersHolder
353
```