or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

annotations.mdapplication-context.mdbean-definition.mdbean-factory.mdbean-processing.mdbean-providers.mdenvironment-config.mdevents.mdexceptions.mdindex.mdscoping.md

environment-config.mddocs/

0

# Configuration and Environment

1

2

The Micronaut environment and configuration system provides a powerful way to manage application settings, property sources, and environment-specific configurations. It supports property resolution from multiple sources with type conversion and validation.

3

4

## Core Interfaces

5

6

### Environment

7

8

Main interface for accessing application environment and configuration properties.

9

10

```java { .api }

11

public interface Environment extends PropertyResolver {

12

String DEVELOPMENT = "dev";

13

String TEST = "test";

14

String PRODUCTION = "prod";

15

16

Collection<String> getActiveNames();

17

Set<String> getPackages();

18

<T> Optional<T> getProperty(String name, Class<T> requiredType);

19

<T> T getProperty(String name, Class<T> requiredType, T defaultValue);

20

boolean containsProperty(String name);

21

boolean containsProperties(String name);

22

Collection<PropertySource> getPropertySources();

23

Environment addPropertySource(PropertySource propertySource);

24

Environment removePropertySource(PropertySource propertySource);

25

}

26

```

27

28

### PropertyResolver

29

30

Interface for resolving properties from various sources with type conversion.

31

32

```java { .api }

33

public interface PropertyResolver {

34

boolean containsProperty(String name);

35

boolean containsProperties(String name);

36

<T> Optional<T> getProperty(String name, Class<T> requiredType);

37

<T> T getProperty(String name, Class<T> requiredType, T defaultValue);

38

String getProperty(String name, String defaultValue);

39

<T> Optional<T> getProperty(String name, ArgumentConversionContext<T> conversionContext);

40

String resolvePlaceholders(String str);

41

String resolveRequiredPlaceholders(String str) throws ConfigurationException;

42

<T> T getRequiredProperty(String name, Class<T> requiredType) throws ConfigurationException;

43

}

44

```

45

46

### PropertySource

47

48

Represents a source of configuration properties.

49

50

```java { .api }

51

public interface PropertySource {

52

String getName();

53

Object get(String key);

54

Iterator<String> iterator();

55

int getOrder();

56

PropertyConvention getConvention();

57

58

static PropertySource of(String name, Map<String, Object> values);

59

static PropertySource of(Map<String, Object> values);

60

}

61

```

62

63

## Property Resolution

64

65

### Basic Property Access

66

67

```java

68

import io.micronaut.context.ApplicationContext;

69

import io.micronaut.context.env.Environment;

70

71

public class BasicPropertyExample {

72

public static void main(String[] args) {

73

try (ApplicationContext context = ApplicationContext.run()) {

74

Environment env = context.getEnvironment();

75

76

// Get string property with default

77

String appName = env.getProperty("app.name", String.class, "DefaultApp");

78

79

// Get typed property

80

Integer port = env.getProperty("server.port", Integer.class, 8080);

81

82

// Get boolean property

83

Boolean debug = env.getProperty("app.debug", Boolean.class, false);

84

85

// Check if property exists

86

if (env.containsProperty("database.url")) {

87

String dbUrl = env.getProperty("database.url", String.class);

88

System.out.println("Database URL: " + dbUrl);

89

}

90

91

System.out.println("App: " + appName + ", Port: " + port + ", Debug: " + debug);

92

}

93

}

94

}

95

```

96

97

### Required Properties

98

99

```java

100

import io.micronaut.context.ApplicationContext;

101

import io.micronaut.context.env.Environment;

102

import io.micronaut.context.exceptions.ConfigurationException;

103

104

public class RequiredPropertyExample {

105

public static void main(String[] args) {

106

try (ApplicationContext context = ApplicationContext.run()) {

107

Environment env = context.getEnvironment();

108

109

try {

110

// Get required property - throws exception if missing

111

String apiKey = env.getRequiredProperty("api.key", String.class);

112

System.out.println("API Key configured: " + apiKey.substring(0, 4) + "...");

113

114

} catch (ConfigurationException e) {

115

System.err.println("Missing required configuration: " + e.getMessage());

116

}

117

}

118

}

119

}

120

```

121

122

### Property Placeholder Resolution

123

124

```java

125

import io.micronaut.context.ApplicationContext;

126

import io.micronaut.context.env.Environment;

127

128

public class PlaceholderExample {

129

public static void main(String[] args) {

130

try (ApplicationContext context = ApplicationContext.run()) {

131

Environment env = context.getEnvironment();

132

133

// Resolve placeholders in strings

134

String template = "Welcome to ${app.name} running on port ${server.port:8080}";

135

String resolved = env.resolvePlaceholders(template);

136

System.out.println(resolved);

137

138

// Required placeholder resolution

139

try {

140

String requiredTemplate = "Database: ${database.url}";

141

String requiredResolved = env.resolveRequiredPlaceholders(requiredTemplate);

142

System.out.println(requiredResolved);

143

} catch (ConfigurationException e) {

144

System.err.println("Failed to resolve placeholder: " + e.getMessage());

145

}

146

}

147

}

148

}

149

```

150

151

## Environment Management

152

153

### Active Environments

154

155

```java

156

import io.micronaut.context.ApplicationContext;

157

import io.micronaut.context.env.Environment;

158

159

public class EnvironmentExample {

160

public static void main(String[] args) {

161

try (ApplicationContext context = ApplicationContext.run("dev", "local")) {

162

Environment env = context.getEnvironment();

163

164

// Get active environment names

165

Collection<String> activeEnvironments = env.getActiveNames();

166

System.out.println("Active environments: " + activeEnvironments);

167

168

// Check for specific environment

169

if (activeEnvironments.contains(Environment.DEVELOPMENT)) {

170

System.out.println("Running in development mode");

171

}

172

173

// Environment-specific configuration

174

if (activeEnvironments.contains("local")) {

175

String localDbUrl = env.getProperty("database.url", String.class, "jdbc:h2:mem:test");

176

System.out.println("Local database: " + localDbUrl);

177

}

178

}

179

}

180

}

181

```

182

183

### Package Scanning

184

185

```java

186

import io.micronaut.context.ApplicationContext;

187

import io.micronaut.context.env.Environment;

188

189

public class PackageExample {

190

public static void main(String[] args) {

191

try (ApplicationContext context = ApplicationContext.run()) {

192

Environment env = context.getEnvironment();

193

194

// Get scanned packages

195

Set<String> packages = env.getPackages();

196

System.out.println("Scanned packages: " + packages);

197

}

198

}

199

}

200

```

201

202

## Property Sources

203

204

### Working with Property Sources

205

206

```java

207

import io.micronaut.context.ApplicationContext;

208

import io.micronaut.context.env.Environment;

209

import io.micronaut.context.env.PropertySource;

210

import java.util.Map;

211

212

public class PropertySourceExample {

213

public static void main(String[] args) {

214

try (ApplicationContext context = ApplicationContext.run()) {

215

Environment env = context.getEnvironment();

216

217

// Get all property sources

218

Collection<PropertySource> sources = env.getPropertySources();

219

for (PropertySource source : sources) {

220

System.out.println("Property source: " + source.getName() +

221

" (order: " + source.getOrder() + ")");

222

}

223

224

// Add custom property source

225

PropertySource customSource = PropertySource.of("custom", Map.of(

226

"custom.setting", "value",

227

"app.feature.enabled", true

228

));

229

230

env.addPropertySource(customSource);

231

232

// Access custom property

233

String customSetting = env.getProperty("custom.setting", String.class);

234

System.out.println("Custom setting: " + customSetting);

235

}

236

}

237

}

238

```

239

240

### Creating Property Sources

241

242

```java

243

import io.micronaut.context.env.PropertySource;

244

import java.util.Map;

245

import java.util.HashMap;

246

247

public class CustomPropertySourceExample {

248

249

public static PropertySource createDatabasePropertySource() {

250

Map<String, Object> props = new HashMap<>();

251

props.put("datasources.default.url", "jdbc:postgresql://localhost/myapp");

252

props.put("datasources.default.username", "appuser");

253

props.put("datasources.default.driverClassName", "org.postgresql.Driver");

254

255

return PropertySource.of("database-config", props);

256

}

257

258

public static PropertySource createFeatureFlags() {

259

return PropertySource.of("feature-flags", Map.of(

260

"features.new-ui", true,

261

"features.beta-api", false,

262

"features.analytics", true

263

));

264

}

265

}

266

```

267

268

## Configuration Properties

269

270

### @ConfigurationProperties Usage

271

272

```java

273

import io.micronaut.context.annotation.ConfigurationProperties;

274

import jakarta.validation.constraints.NotBlank;

275

import jakarta.validation.constraints.Min;

276

import jakarta.validation.constraints.Max;

277

278

@ConfigurationProperties("database")

279

public class DatabaseConfig {

280

281

@NotBlank

282

private String url;

283

284

@NotBlank

285

private String username;

286

287

private String password;

288

289

@Min(1)

290

@Max(100)

291

private int maxConnections = 10;

292

293

private boolean ssl = false;

294

295

// Getters and setters

296

public String getUrl() { return url; }

297

public void setUrl(String url) { this.url = url; }

298

299

public String getUsername() { return username; }

300

public void setUsername(String username) { this.username = username; }

301

302

public String getPassword() { return password; }

303

public void setPassword(String password) { this.password = password; }

304

305

public int getMaxConnections() { return maxConnections; }

306

public void setMaxConnections(int maxConnections) { this.maxConnections = maxConnections; }

307

308

public boolean isSsl() { return ssl; }

309

public void setSsl(boolean ssl) { this.ssl = ssl; }

310

}

311

```

312

313

### Nested Configuration Properties

314

315

```java

316

import io.micronaut.context.annotation.ConfigurationProperties;

317

import java.time.Duration;

318

319

@ConfigurationProperties("app")

320

public class ApplicationConfig {

321

322

private String name;

323

private String version;

324

private Server server = new Server();

325

private Security security = new Security();

326

327

@ConfigurationProperties("server")

328

public static class Server {

329

private int port = 8080;

330

private String host = "localhost";

331

private Duration timeout = Duration.ofSeconds(30);

332

333

// Getters and setters

334

public int getPort() { return port; }

335

public void setPort(int port) { this.port = port; }

336

337

public String getHost() { return host; }

338

public void setHost(String host) { this.host = host; }

339

340

public Duration getTimeout() { return timeout; }

341

public void setTimeout(Duration timeout) { this.timeout = timeout; }

342

}

343

344

@ConfigurationProperties("security")

345

public static class Security {

346

private boolean enabled = true;

347

private String algorithm = "SHA-256";

348

349

// Getters and setters

350

public boolean isEnabled() { return enabled; }

351

public void setEnabled(boolean enabled) { this.enabled = enabled; }

352

353

public String getAlgorithm() { return algorithm; }

354

public void setAlgorithm(String algorithm) { this.algorithm = algorithm; }

355

}

356

357

// Main class getters and setters

358

public String getName() { return name; }

359

public void setName(String name) { this.name = name; }

360

361

public String getVersion() { return version; }

362

public void setVersion(String version) { this.version = version; }

363

364

public Server getServer() { return server; }

365

public void setServer(Server server) { this.server = server; }

366

367

public Security getSecurity() { return security; }

368

public void setSecurity(Security security) { this.security = security; }

369

}

370

```

371

372

### Using Configuration Properties

373

374

```java

375

import io.micronaut.context.ApplicationContext;

376

import jakarta.inject.Singleton;

377

import jakarta.inject.Inject;

378

379

@Singleton

380

public class DatabaseService {

381

private final DatabaseConfig config;

382

383

@Inject

384

public DatabaseService(DatabaseConfig config) {

385

this.config = config;

386

}

387

388

public void connect() {

389

System.out.println("Connecting to: " + config.getUrl());

390

System.out.println("Username: " + config.getUsername());

391

System.out.println("Max connections: " + config.getMaxConnections());

392

System.out.println("SSL enabled: " + config.isSsl());

393

}

394

}

395

396

public class ConfigurationExample {

397

public static void main(String[] args) {

398

try (ApplicationContext context = ApplicationContext.run()) {

399

DatabaseService service = context.getBean(DatabaseService.class);

400

service.connect();

401

}

402

}

403

}

404

```

405

406

## Value Injection

407

408

### @Value Annotation

409

410

```java

411

import io.micronaut.context.annotation.Value;

412

import jakarta.inject.Singleton;

413

414

@Singleton

415

public class ServiceWithValues {

416

417

@Value("${app.name:DefaultApp}")

418

private String appName;

419

420

@Value("${server.port:8080}")

421

private int serverPort;

422

423

@Value("${app.debug:false}")

424

private boolean debugMode;

425

426

@Value("${app.version}")

427

private String version; // Required property - no default

428

429

public void displayConfig() {

430

System.out.println("App: " + appName);

431

System.out.println("Port: " + serverPort);

432

System.out.println("Debug: " + debugMode);

433

System.out.println("Version: " + version);

434

}

435

}

436

```

437

438

### @Property Annotation

439

440

```java

441

import io.micronaut.context.annotation.Property;

442

import jakarta.inject.Singleton;

443

444

@Singleton

445

public class PropertyInjectionExample {

446

447

private final String databaseUrl;

448

private final Integer connectionTimeout;

449

450

public PropertyInjectionExample(

451

@Property(name = "database.url") String databaseUrl,

452

@Property(name = "database.timeout", defaultValue = "30") Integer connectionTimeout) {

453

454

this.databaseUrl = databaseUrl;

455

this.connectionTimeout = connectionTimeout;

456

}

457

458

public void printConfiguration() {

459

System.out.println("Database URL: " + databaseUrl);

460

System.out.println("Connection timeout: " + connectionTimeout + "s");

461

}

462

}

463

```

464

465

## Type Conversion

466

467

### Built-in Type Conversion

468

469

```java

470

import io.micronaut.context.ApplicationContext;

471

import io.micronaut.context.env.Environment;

472

import java.time.Duration;

473

import java.time.LocalDateTime;

474

import java.util.List;

475

476

public class TypeConversionExample {

477

public static void main(String[] args) {

478

try (ApplicationContext context = ApplicationContext.run()) {

479

Environment env = context.getEnvironment();

480

481

// Duration conversion (e.g., "30s", "5m", "1h")

482

Duration timeout = env.getProperty("app.timeout", Duration.class, Duration.ofSeconds(30));

483

484

// List conversion (comma-separated values)

485

List<String> tags = env.getProperty("app.tags", List.class);

486

487

// LocalDateTime conversion

488

LocalDateTime startTime = env.getProperty("app.start-time", LocalDateTime.class);

489

490

System.out.println("Timeout: " + timeout);

491

System.out.println("Tags: " + tags);

492

System.out.println("Start time: " + startTime);

493

}

494

}

495

}

496

```

497

498

## Implementation Classes

499

500

### DefaultEnvironment

501

502

Default implementation of the Environment interface.

503

504

```java { .api }

505

public class DefaultEnvironment implements Environment {

506

public DefaultEnvironment(ApplicationContextConfiguration configuration);

507

508

// Implements Environment interface methods

509

public Collection<String> getActiveNames();

510

public <T> Optional<T> getProperty(String name, Class<T> requiredType);

511

public boolean containsProperty(String name);

512

public Collection<PropertySource> getPropertySources();

513

}

514

```