Create a Spring App with Maven
In case, if you are not going to use Spring boot for some reason and want to create a Spring app from scratch, below are the steps to create one using Maven as a build tool
1. Setup pom.xml
You may configure a Java-Maven project in your IDE and then spring dependency or you may wire things up from the XML file.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>spring-plain-ioc</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>23</maven.compiler.source>
<maven.compiler.target>23</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.1.14</version> <!-- this is the spring dependency -->
</dependency>
</dependencies>
</project>
2. Create your Config and POJO class
We will add the configuration using Java config. To make things simple, lets add the POJO classes and the wire up the Beans inside the AppConfig class. In our example, we are creating a bean vehicle which is wired up with Engine as a dependency
package org.example;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
record Vehicle(String name, Engine engine) {};
record Engine(String type, int power) {};
@Configuration
public class AppConfig {
@Bean(name = "vehicle")
public Vehicle vehicle() {
return new Vehicle("vehicle1", new Engine("engine1", 1));
}
}
3. Start your app using AnnotationConfigApplicationContext container
Since we have used a Java Config, we will use the AnnotationConfigApplicationContext IOC container for DI. Finally we fetch the bean using the context.
public class Main {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
Vehicle v1 = context.getBean(Vehicle.class);
System.out.println(v1.name());
}
}