DEV Community

anand jaisy
anand jaisy

Posted on

Java 25 Compact Source Files: Simplifying Micronaut Application Startup

Compact source file

In Java, a compact source file is a feature finalized in Java 25 (via JEP 512) that allows you to write a launchable Java program without explicitly declaring a class or a public static void main method. It is designed to minimize boilerplate code.

How this is useful with Micronaut application. When you create a project using micronaut application Micronaut

The project structure is always same for all the framework, either spring, micronuat, quarkus, helidon or something else

The traditional approach

package com.example;

import io.micronaut.runtime.Micronaut;

public class Application {

    public static void main(String[] args) {
        Micronaut.run(Application.class, args);
    }
}
Enter fullscreen mode Exit fullscreen mode

The corresponding Gradle configuration commonly specifies the application's main class:build.gradle.kt

application {
    mainClass = "com.example.Application"
}
Enter fullscreen mode Exit fullscreen mode

Using a Compact Source File
With Java 25, the same entry point can be expressed using a compact source file:

Application.java

import io.micronaut.runtime.Micronaut;

void main() {
    Micronaut.run();
}
Enter fullscreen mode Exit fullscreen mode

There is no explicit:

  • package declaration
  • class declaration
  • public static void main(...) method declaration

Configuring Micronaut

Because the compact source file does not declare a package, the fully qualified class name used in the Gradle configuration is no longer required.

application {
    mainClass = "Application"
}
Enter fullscreen mode Exit fullscreen mode

The implicit class takes its name from the file name, so the file name and mainClass have to match exactly. Also, put the file in a source directory that isn't nested under a packages/ folder, or move it to the root of src/main/java. javac doesn't strictly enforce directory structure, but IDEs and incremental compilation behave better when the layout matches.

src/ 
└── main/ 
      └── java/ 
            └── Application.java
Enter fullscreen mode Exit fullscreen mode

Top comments (0)