Hello World with Spring Framework 7 and Spring Boot 4

A Spring application is a container that creates your objects and wires them together. This page builds the smallest useful one four times: with plain Spring Framework and Java configuration, with the classic XML file, as a Spring Boot console program and as a Spring Boot REST service, then looks at what Spring Boot set up behind the scenes and the mistakes that trip up a first project.

Contents

What a Spring application is made of

Every Spring application, from a ten-line program to a large web service, has the same three parts. There are your classes, written as plain Java with constructors. There is configuration that tells Spring which of those classes to manage, written as annotations, Java methods or XML. And there is the container, the ApplicationContext, which reads the configuration, creates the objects (called beans), passes each one the others it needs, and closes them at the end. The inversion of control page explains the container in depth.

Spring Framework provides the container and the libraries around it: web, data access, transactions. Spring Boot is built on top. It chooses compatible versions of everything, configures the usual beans automatically from what is on the classpath, and starts an embedded web server, so a working service needs one class and one dependency.

Spring Framework and Spring Boot for a first application
Spring Framework 7.0Spring Boot 4.1
Dependency to addspring-contextA starter, such as spring-boot-starter-webmvc
Container created byYou: new AnnotationConfigApplicationContext(...)SpringApplication.run(...)
ConfigurationEverything explicitAuto-configuration, adjusted with properties
Web serverDeployed to an external servlet containerEmbedded Tomcat, started for you
Minimum Java version1717
Best forLibraries, small tools, learning how the container worksApplications and services

Both run on Jakarta EE 11 APIs, so imports start with jakarta., not javax.; code copied from tutorials for Spring 5 or Boot 2 needs that change. The programs below were run with Java 21 against Spring Framework 7.0.10 and Spring Boot 4.1.2.

Setting up the project

For plain Spring, one dependency brings the container, with spring-core, spring-beans, spring-aop and spring-expression as its own dependencies:

XML
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>7.0.10</version>
</dependency>

For Spring Boot, inherit from the parent POM, which manages the versions of every library and configures the compiler and the packaging plugin, and add the starter for a Spring MVC web application:

XML
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>4.1.2</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-webmvc</artifactId>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

Spring Boot 4 renamed the web starter: spring-boot-starter-web from Boot 3 still exists, but is deprecated in favour of spring-boot-starter-webmvc. A console program without a web server needs only spring-boot-starter. The parent POM also configures the compiler plugin with <parameters>true</parameters>, which compiles with javac -parameters. Spring MVC relies on it to match @RequestParam String name to the query parameter name; without the flag, those requests fail with an error asking for -parameters. The Spring Boot examples below were compiled with it.

The Spring Initializr, at start.spring.io or in most IDEs, generates the same project with Maven or Gradle, including a main class and a test. The XML above was checked against the 4.1.2 POMs, but no Maven build was run for this page; the programs were compiled and run directly with javac and java.

Hello World with plain Spring

The smallest Spring program has one configuration class and two beans, one of which depends on the other, so that the container has something to wire:

Java
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

public class HelloSpring {

    interface Salutation {
        String text();
    }

    static class GreetingService {
        private final Salutation salutation;

        GreetingService(Salutation salutation) {
            this.salutation = salutation;
        }

        String greet(String name) {
            return salutation.text() + ", " + name + "!";
        }
    }

    @Configuration
    static class AppConfig {
        @Bean
        Salutation salutation() {
            return () -> "Hello";
        }

        @Bean
        GreetingService greetingService(Salutation salutation) {
            return new GreetingService(salutation);
        }
    }

    public static void main(String[] args) {
        try (var context = new AnnotationConfigApplicationContext(AppConfig.class)) {
            GreetingService service = context.getBean(GreetingService.class);
            System.out.println(service.greet("World"));
            System.out.println("GreetingService bean class: "
                    + service.getClass().getSimpleName());
        }
    }
}
Output
Hello, World!
GreetingService bean class: GreetingService
  • new AnnotationConfigApplicationContext(AppConfig.class) started the container. It read the two @Bean methods, created the Salutation first, and passed it to greetingService because that method asks for one as a parameter.
  • getBean(GreetingService.class) returned the managed object, and greet("World") printed Hello, World!.
  • The bean's class is plain GreetingService: Spring did not wrap it, because nothing such as @Transactional asked for a proxy.
  • The try-with-resources block closes the context at the end, which destroys the beans in reverse order.

Nothing in GreetingService refers to Spring. It is an ordinary class with a constructor, which is the point: the container does the wiring, and the class stays easy to test and reuse. The Java configuration page covers @Configuration and @Bean in detail.

The same with XML configuration

Before Java configuration arrived in Spring 3.0, beans were declared in XML, and many older applications still are. Spring Framework 7 reads XML as it always did. This program keeps the XML in a text block, so that it runs without a resource file. In a project it would be src/main/resources/beans.xml, loaded with new GenericXmlApplicationContext("classpath:beans.xml"):

Java
import java.nio.charset.StandardCharsets;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.core.io.ByteArrayResource;

public class HelloXml {

    // Usually this is a file such as src/main/resources/beans.xml
    static final String BEANS_XML = """
            <beans xmlns="http://www.springframework.org/schema/beans"
                   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                   xsi:schemaLocation="http://www.springframework.org/schema/beans
                       https://www.springframework.org/schema/beans/spring-beans.xsd">
                <bean id="tom" class="HelloXml$Person"
                      init-method="ready" destroy-method="leave">
                    <property name="firstName" value="Tom"/>
                    <property name="lastName" value="Cruise"/>
                </bean>
            </beans>
            """;

    public static class Person {
        private String firstName;
        private String lastName;

        public void setFirstName(String firstName) {
            this.firstName = firstName;
        }

        public void setLastName(String lastName) {
            this.lastName = lastName;
        }

        public void ready() {
            System.out.println("init-method: " + firstName + " " + lastName + " is ready");
        }

        public void leave() {
            System.out.println("destroy-method: " + firstName + " leaves");
        }

        @Override
        public String toString() {
            return "Person " + firstName + " " + lastName;
        }
    }

    public static void main(String[] args) {
        var xml = new ByteArrayResource(BEANS_XML.getBytes(StandardCharsets.UTF_8));
        try (var context = new GenericXmlApplicationContext(xml)) {
            Person tom = context.getBean("tom", Person.class);
            System.out.println("getBean(\"tom\"): " + tom);
        }
    }
}
Output
init-method: Tom Cruise is ready
getBean("tom"): Person Tom Cruise
destroy-method: Tom leaves
  • The <bean id="tom"> element created a Person with its no-argument constructor, then called setFirstName("Tom") and setLastName("Cruise") for the two <property> elements.
  • init-method="ready" ran after the properties were set, so it could already print the full name. destroy-method="leave" ran when the context closed, after the bean was used.
  • getBean("tom", Person.class) looked the bean up by its id and checked its type.

The class name in XML is a string, so a typo or a renamed class shows up only when the context starts, not when the code compiles. That is the main reason new code uses Java configuration. The XML schema is still supported, and @ImportResource lets a Java configuration load an existing XML file during a migration.

Hello World with Spring Boot

With Spring Boot, the application is one annotated class, and the beans are found by scanning its package. A CommandLineRunner bean runs once the context is ready, which suits a console program:

Java
package hello.console;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

@SpringBootApplication
public class HelloBoot {

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(HelloBoot.class);
        app.setWebApplicationType(WebApplicationType.NONE);   // see the note below the output
        try (var context = app.run("--spring.main.banner-mode=off",
                "--logging.level.root=WARN", "--greeting.name=Spring Boot")) {
            System.out.println("Context class: " + context.getClass().getSimpleName());
        }
    }
}

@Service
class GreetingService {
    private final String name;

    GreetingService(@Value("${greeting.name:World}") String name) {
        this.name = name;
    }

    String greet() {
        return "Hello, " + name + "!";
    }
}

@Component
class GreetingRunner implements CommandLineRunner {
    private final GreetingService service;

    GreetingRunner(GreetingService service) {
        this.service = service;
    }

    @Override
    public void run(String... args) {
        System.out.println(service.greet());
        System.out.println("Arguments passed to the runner: " + String.join(" ", args));
    }
}
Output
Hello, Spring Boot!
Arguments passed to the runner: --spring.main.banner-mode=off --logging.level.root=WARN --greeting.name=Spring Boot
Context class: AnnotationConfigApplicationContext
  • @SpringBootApplication combines @SpringBootConfiguration, @EnableAutoConfiguration and @ComponentScan. The scan found GreetingService and GreetingRunner in the package hello.console without any @Bean methods.
  • The --greeting.name=Spring Boot argument became a property, and @Value("${greeting.name:World}") injected it, so the greeting was Hello, Spring Boot!. Without the argument, the default after the colon, World, would be used. In a project, the same property usually lives in src/main/resources/application.properties.
  • The runner received the command-line arguments that run was given, all three of them.
  • The runner ran inside run, before it returned, and the context was then closed by the try-with-resources block. Without a web server or other running threads, a Boot console program exits when main ends.

The context is a plain AnnotationConfigApplicationContext because the program sets WebApplicationType.NONE. That is needed here only because this page runs all its programs on one classpath, which includes Tomcat for the next example. A project that depends on spring-boot-starter alone gets the same non-web context without that line. The two arguments for the banner and logging only keep the output short; a normal run prints the Spring Boot banner and a few startup log lines.

A REST service with Spring Boot

Adding spring-boot-starter-webmvc and a @RestController turns the application into a web service. The program starts it on a random free port (server.port=0), sends five requests with Java's HttpClient, prints each response and shuts down. The fifth request goes to a controller in another package, shown after the output:

Java
package hello.web;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
public class HelloWeb {

    public static void main(String[] args) throws Exception {
        try (var context = SpringApplication.run(HelloWeb.class, "--server.port=0",
                "--spring.main.banner-mode=off", "--logging.level.root=ERROR")) {
            var server = ((WebServerApplicationContext) context).getWebServer();
            System.out.println("Web server: " + server.getClass().getSimpleName());
            String base = "http://localhost:" + server.getPort();
            HttpClient client = HttpClient.newHttpClient();
            for (String path : new String[] {"/hello", "/hello?name=Ana", "/greeting?name=Ana",
                    "/greeting", "/extra"}) {
                HttpResponse<String> response = client.send(
                        HttpRequest.newBuilder(URI.create(base + path)).build(),
                        HttpResponse.BodyHandlers.ofString());
                System.out.println("GET " + path);
                System.out.println("  " + response.statusCode() + " "
                        + response.headers().firstValue("Content-Type").orElse("-"));
                // error bodies also hold a "timestamp" field, removed here because it varies
                System.out.println("  " + response.body()
                        .replaceFirst("\"timestamp\":\"[^\"]*\",", ""));
            }
        }
    }
}

record Greeting(String message, int length) {
}

@RestController
class HelloController {

    @GetMapping("/hello")
    String hello(@RequestParam(defaultValue = "World") String name) {
        return "Hello, " + name + "!";
    }

    @GetMapping("/greeting")
    Greeting greeting(@RequestParam String name) {
        String message = "Hello, " + name + "!";
        return new Greeting(message, message.length());
    }
}
Output
Web server: TomcatWebServer
GET /hello
  200 text/plain;charset=UTF-8
  Hello, World!
GET /hello?name=Ana
  200 text/plain;charset=UTF-8
  Hello, Ana!
GET /greeting?name=Ana
  200 application/json
  {"message":"Hello, Ana!","length":11}
GET /greeting
  400 application/json
  {"status":400,"error":"Bad Request","path":"/greeting"}
GET /extra
  404 application/json
  {"status":404,"error":"Not Found","path":"/extra"}
  • Spring Boot started an embedded Tomcat, TomcatWebServer. No server was installed or configured; the starter put Tomcat on the classpath and auto-configuration started it.
  • GET /hello returned 200 with text/plain and Hello, World!, using the defaultValue of the parameter. With ?name=Ana it returned Hello, Ana!.
  • GET /greeting?name=Ana returned the Greeting record as JSON, {"message":"Hello, Ana!","length":11}, with application/json. Spring Boot 4 uses Jackson 3 to write it.
  • GET /greeting without name returned 400 Bad Request: the parameter is required unless it has a default or is marked required = false.
  • GET /extra returned 404, although a controller for /extra exists. It is in the package hello.extra, which is not below hello.web, so component scanning never found it.
  • The error bodies are Spring Boot's default JSON error format. The real responses also contain a timestamp field, which the program removes because it changes on every run. The logging level is ERROR so that the warning Spring logs for the 400 response does not appear.
Java
package hello.extra;   // a sibling of hello.web, not below it

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ExtraController {

    @GetMapping("/extra")
    public String extra() {
        return "never reached";
    }
}

To find that controller, move it to hello.web.extra or another package below the main class, or name the package with @SpringBootApplication(scanBasePackages = "hello"). Keeping the main class in the root package of the application avoids the problem altogether.

What Spring Boot configured behind the scenes

The REST service declared one controller, yet a working web server, a JSON mapper and an error page appeared. They come from auto-configuration: classes that Boot loads from every jar on the classpath, each guarded by conditions such as "this class is present" or "no bean of this type was defined". The condition evaluation report records every decision. This program starts the same kind of application and reads that report:

Java
package hello.inside;

import java.util.List;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.condition.ConditionEvaluationReport;
import org.springframework.boot.web.server.context.WebServerApplicationContext;

@SpringBootApplication
public class BootInsideOut {

    public static void main(String[] args) {
        try (var context = SpringApplication.run(BootInsideOut.class, "--server.port=0",
                "--spring.main.banner-mode=off", "--logging.level.root=WARN")) {
            System.out.println("Context class   : " + context.getClass().getSimpleName());
            System.out.println("Is a web context: "
                    + (context instanceof WebServerApplicationContext));
            System.out.println("Beans defined   : " + context.getBeanDefinitionCount());

            var report = ConditionEvaluationReport.get(context.getBeanFactory());
            var outcomes = report.getConditionAndOutcomesBySource();
            long matched = outcomes.values().stream().filter(o -> o.isFullMatch()).count();
            System.out.println("Auto-configuration classes and @Bean methods evaluated: "
                    + outcomes.size() + ", matched: " + matched);

            for (String name : List.of("DispatcherServletAutoConfiguration",
                    "TomcatServletWebServerAutoConfiguration", "JacksonAutoConfiguration",
                    "DataSourceAutoConfiguration", "SecurityAutoConfiguration")) {
                String key = outcomes.keySet().stream()
                        .filter(source -> source.endsWith("." + name)).findFirst().orElse(null);
                String result = key == null ? "not on the classpath"
                        : outcomes.get(key).isFullMatch() ? "matched" : "did not match";
                System.out.printf("  %-40s %s%n", name, result);
            }
            System.out.println("Some beans it created: "
                    + context.containsBean("dispatcherServlet") + " dispatcherServlet, "
                    + context.getBeanNamesForType(tools.jackson.databind.json.JsonMapper.class)
                            .length + " JsonMapper");
        }
    }
}
Output
Context class   : AnnotationConfigServletWebServerApplicationContext
Is a web context: true
Beans defined   : 145
Auto-configuration classes and @Bean methods evaluated: 91, matched: 52
  DispatcherServletAutoConfiguration       matched
  TomcatServletWebServerAutoConfiguration  matched
  JacksonAutoConfiguration                 matched
  DataSourceAutoConfiguration              not on the classpath
  SecurityAutoConfiguration                not on the classpath
Some beans it created: true dispatcherServlet, 1 JsonMapper
  • The context is an AnnotationConfigServletWebServerApplicationContext, a web context that starts its own server. Boot chose it because the servlet API and Spring MVC are on the classpath.
  • The application declares no beans of its own, yet the context holds 145 definitions. Almost all of them come from auto-configuration.
  • Of the 91 auto-configuration classes and conditional methods that were evaluated, 52 matched. DispatcherServletAutoConfiguration, TomcatServletWebServerAutoConfiguration and JacksonAutoConfiguration matched and created the dispatcher servlet, the server and the JsonMapper.
  • DataSourceAutoConfiguration and SecurityAutoConfiguration were not even evaluated. Spring Boot 4 splits auto-configuration into modules, such as spring-boot-jdbc and spring-boot-security, and those modules arrive only with their starters.

The exact numbers depend on the jars on the classpath, so they differ between projects. To see the same report for your own application, start it with --debug, or set debug=true in application.properties: Boot then logs the matched and unmatched auto-configurations with the reason for each. Any bean you define yourself replaces the auto-configured one of the same type in most cases, because the auto-configured beans are guarded by @ConditionalOnMissingBean.

Running and packaging

In a Maven project, these commands start and package the application. They are standard Spring Boot plugin goals, but they were not run for this page:

Shell
./mvnw spring-boot:run                     # compile and start
./mvnw package                             # build target/<name>-<version>.jar
java -jar target/hello-0.0.1-SNAPSHOT.jar  # run the executable jar
java -jar target/hello-0.0.1-SNAPSHOT.jar --server.port=9090 --greeting.name=Ana

The packaged jar contains the application and all its dependencies, including Tomcat, so it runs anywhere Java 17 or later is installed. Command-line arguments such as --server.port=9090 override properties from application.properties, exactly as the arguments in the programs above did. A web application keeps running until it is stopped, for example with Ctrl+C, which closes the context and its beans in order.

Mistakes in a first project

  • Main class in the default package: @SpringBootApplication on a class with no package statement scans every jar on the classpath. Spring Boot warns about it, and startup is slow or fails. Always give the main class a package.
  • Classes outside the scanned package: as /extra showed, a controller or service in a sibling package is silently ignored. The symptom is a 404 or a missing bean.
  • Port 8080 already in use: a second copy of the application, or another server, holds the default port, and startup fails with a message that the port was already in use. Stop the other process, or set server.port.
  • A bean named messageSource: Spring reserves some bean names. A @Bean method called messageSource that returns a type of your own stops the context from starting with BeanNotOfRequiredTypeException, because the context expects that name to be Spring's MessageSource. The plain Spring example above calls its bean salutation for this reason.
  • javax imports: javax.annotation.PostConstruct or javax.servlet from old examples either do not compile or are ignored. Use the jakarta packages.
  • Mixing Boot versions: declaring versions for individual Spring or Boot jars, instead of letting the parent POM manage them, easily produces a mix that fails at startup with NoSuchMethodError or ClassNotFoundException.

Choosing a starting point

Which kind of first application to write
GoalStart with
A web service or web applicationSpring Boot with spring-boot-starter-webmvc
A command-line tool or batch jobSpring Boot with spring-boot-starter and a CommandLineRunner
Learning how the container worksPlain Spring with AnnotationConfigApplicationContext
A library that uses Spring internallyPlain Spring Framework dependencies, no Boot
Maintaining an XML-configured applicationGenericXmlApplicationContext, moving to Java configuration step by step
A reactive, non-blocking serviceSpring Boot with spring-boot-starter-webflux

From here, the dependency injection page explains how beans receive each other, Spring annotations covers @Component and scanning, bean lifecycle shows the init and destroy callbacks, and REST controllers goes further with the web layer.