void main(String[] args)
{
System.out.println("Hello world");
}
Starting with modern Java versions (formalized as a permanent feature in Java 25), the language introduced Instance Main Methods and Implicitly Declared Classes.
The above code works because the Java compiler and launcher now allow you to omit traditional boilerplate code for small or introductory programs:
Implicitly Declared Classes (Unnamed Classes): If you write code directly in a .java file without a explicit public class ClassName wrapper, Java treats everything as part of an unnamed, top-level class automatically.
Instance Main Methods: The JVM launcher no longer strictly requires the public static void main(String[] args) signature. It can now recognize and execute instance methods named main (even without public, static, or String[] args). Under the hood, the compiler wraps your file into a hidden class, instantiates it via a zero-argument constructor, and invokes your instance main() method.
What if an enterprise application has multiple classes with a main method?
In a standard enterprise application (like a Spring Boot application running on an embedded server or deployed to an application server like Apache Tomcat), having multiple classes with a main method does not cause a conflict or confuse the container.
Here is why and how execution is determined depending on the context:
1. How Tomcat or Servlet Containers Start Up
Apache Tomcat does not look for or execute a main(String[] args) method when it boots up an enterprise web application.
Instead, Tomcat looks at your application's deployment descriptor (
WEB-INF/web.xml) or relies on Servlet Container Initializers (ServletContainerInitializer) and Spring'sSpringServletContainerInitializer.When deployed as a WAR file, the entry point is typically a class implementing
WebApplicationInitializer(or extendingSpringBootServletInitializer), which hooks directly into the servlet lifecycle. Tomcat invokes lifecycle callback methods (likeonStartup()), completely bypassing anymainmethods.
2. How Spring Boot Standalone Applications Know What to Run
If you run your enterprise application as a standalone executable JAR using java -jar, Spring Boot looks at the MANIFEST.MF file inside the META-INF directory.
The manifest explicitly declares the startup entry point via the
Start-ClassorMain-Classattribute (e.g.,Main-Class: org.springframework.boot.loader.JarLauncherand a nested attribute pointing to your actual configuration class likecom.example.Application).Even if you have 50 different utility classes containing their own
mainmethods across various packages, the JVM and Spring Boot launcher only execute the single class specified in that manifest file. If you try to run the JAR without specifying a unique target or manifest entry, the build tool (like Maven or Gradle) will typically fail during packaging with a "Multiple main classes found" error.
No comments:
Post a Comment