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 Setting up the project Hello World with plain Spring The same with XML configuration Hello World with Spring Boot A REST service with Spring Boot What Spring Boot configured behind the scenes Running and packaging Mistakes in a first project Choosing a starting point
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
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 7.0 | Spring Boot 4.1 | |
|---|---|---|
| Dependency to add | spring-context | A starter, such as spring-boot-starter-webmvc |
| Container created by | You: new AnnotationConfigApplicationContext(...) | SpringApplication.run(...) |
| Configuration | Everything explicit | Auto-configuration, adjusted with properties |
| Web server | Deployed to an external servlet container | Embedded Tomcat, started for you |
| Minimum Java version | 17 | 17 |
| Best for | Libraries, small tools, learning how the container works | Applications and services |
Both run on Jakarta EE 11 APIs, so imports start with jakarta.javax.
Setting up the project
For plain Spring, one dependency brings the container, with spring-corespring-beansspring-aopspring-expression
<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:
<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-webspring-boot-starter-webmvcspring-boot-starter<parameters>true</parameters>javac -parameters@RequestParam String namename-parameters
The Spring Initializr, at start.spring.iojavacjava
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:
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());
}
}
}
Hello, World!
GreetingService bean class: GreetingService
started the container. It read the twonew AnnotationConfigApplicationContext(AppConfig.class) methods, created the@Bean first, and passed it toSalutation because that method asks for one as a parameter.greetingService returned the managed object, andgetBean(GreetingService.class) printedgreet("World") .Hello, World!- The bean's class is plain
: Spring did not wrap it, because nothing such asGreetingService asked for a proxy.@Transactional - The try-with-resources block closes the context at the end, which destroys the beans in reverse order.
Nothing in GreetingService@Configuration@Bean
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.xmlnew GenericXmlApplicationContext("classpath:beans.xml")
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);
}
}
}
init-method: Tom Cruise is ready
getBean("tom"): Person Tom Cruise
destroy-method: Tom leaves
- The
element created a<bean id="tom"> with its no-argument constructor, then calledPerson andsetFirstName("Tom") for the twosetLastName("Cruise") elements.<property> ran after the properties were set, so it could already print the full name.init-method="ready" ran when the context closed, after the bean was used.destroy-method="leave" looked the bean up by its id and checked its type.getBean("tom", Person.class)
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
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
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));
}
}
Hello, Spring Boot!
Arguments passed to the runner: --spring.main.banner-mode=off --logging.level.root=WARN --greeting.name=Spring Boot
Context class: AnnotationConfigApplicationContext
combines@SpringBootApplication ,@SpringBootConfiguration and@EnableAutoConfiguration . The scan found@ComponentScan andGreetingService in the packageGreetingRunner without anyhello.console methods.@Bean- The
argument became a property, and--greeting.name=Spring Boot injected it, so the greeting was@Value("${greeting.name:World}") . Without the argument, the default after the colon,Hello, Spring Boot! , would be used. In a project, the same property usually lives inWorld .src/main/resources/application.properties - The runner received the command-line arguments that
was given, all three of them.run - The runner ran inside
, 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 whenrun ends.main
The context is a plain AnnotationConfigApplicationContextWebApplicationType.NONEspring-boot-starter
A REST service with Spring Boot
Adding spring-boot-starter-webmvc@RestControllerserver.port=0HttpClient
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());
}
}
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,
. No server was installed or configured; the starter put Tomcat on the classpath and auto-configuration started it.TomcatWebServer returnedGET /hello with200 andtext/plain , using theHello, World! of the parameter. WithdefaultValue it returned?name=Ana .Hello, Ana! returned theGET /greeting?name=Ana record as JSON,Greeting , with{"message":"Hello, Ana!","length":11} . Spring Boot 4 uses Jackson 3 to write it.application/json withoutGET /greeting returnedname : the parameter is required unless it has a default or is marked400 Bad Request .required = false returnedGET /extra , although a controller for404 exists. It is in the package/extra , which is not belowhello.extra , so component scanning never found it.hello.web- The error bodies are Spring Boot's default JSON error format. The real responses also contain a
field, which the program removes because it changes on every run. The logging level istimestamp so that the warning Spring logs for the 400 response does not appear.ERROR
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@SpringBootApplication(scanBasePackages = "hello")
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:
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");
}
}
}
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
, a web context that starts its own server. Boot chose it because the servlet API and Spring MVC are on the classpath.AnnotationConfigServletWebServerApplicationContext - 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 andTomcatServletWebServerAutoConfiguration matched and created the dispatcher servlet, the server and theJacksonAutoConfiguration .JsonMapper andDataSourceAutoConfiguration were not even evaluated. Spring Boot 4 splits auto-configuration into modules, such asSecurityAutoConfiguration andspring-boot-jdbc , and those modules arrive only with their starters.spring-boot-security
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 --debugdebug=trueapplication.properties@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:
./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=9090application.properties
Mistakes in a first project
- Main class in the default package:
on a class with no@SpringBootApplication 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.package - Classes outside the scanned package: as
showed, a controller or service in a sibling package is silently ignored. The symptom is a 404 or a missing bean./extra - 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
method called@Bean that returns a type of your own stops the context from starting withmessageSource , because the context expects that name to be Spring'sBeanNotOfRequiredTypeException . The plain Spring example above calls its beanMessageSource for this reason.salutation - javax imports:
orjavax.annotation.PostConstruct from old examples either do not compile or are ignored. Use thejavax.servlet packages.jakarta - 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
orNoSuchMethodError .ClassNotFoundException
Choosing a starting point
| Goal | Start with |
|---|---|
| A web service or web application | Spring Boot with spring-boot-starter-webmvc |
| A command-line tool or batch job | Spring Boot with spring-boot-starterCommandLineRunner |
| Learning how the container works | Plain Spring with AnnotationConfigApplicationContext |
| A library that uses Spring internally | Plain Spring Framework dependencies, no Boot |
| Maintaining an XML-configured application | GenericXmlApplicationContext |
| A reactive, non-blocking service | Spring Boot with spring-boot-starter-webflux |
From here, the @Component