HelloWorld using Maven + Spring
A step by step guide to create a HelloWorld java application using Spring framework.
Generate project structure with Maven
mvn archetype:generate -DgroupId=net.qstation.springapp -DartifactId=HelloWorld -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
Add Spring dependency
In pom.xml, add
:
<!-- Shared version number properties -->
<properties>
<org.springframework.version>3.1.2.RELEASE</org.springframework.version>
</properties>
:
:
<!-- Spring framework -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
:
Create the bean
Create src/main/java/net/qstation/springapp/HelloWorld.java
package net.qstation.springapp;
/**
* Spring bean
*
*/
public class HelloWorld {
private String name;
public void setName(String name) {
this.name = name;
}
public void printHello() {
System.out.println("Hello ! " + name);
}
}
Configure the bean
Create src/main/resources/HelloWorld-bean.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 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="helloBean" class="net.qstation.springapp.HelloWorld"> <property name="name" value="q-station" /> </bean> </beans>
Create the app
Modify src/main/java/net/qstation/springapp/App.java
package net.qstation.springapp;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
ApplicationContext context = new ClassPathXmlApplicationContext(
"HelloWorld-bean.xml");
HelloWorld obj = (HelloWorld) context.getBean("helloBean");
obj.printHello();
}
}
Package & run it
Plugin one-jar may be use to produce a all in one jar with all dependency included.
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <configuration> <archive> <manifest> <mainClass>net.qstation.springapp.App</mainClass> </manifest> </archive> </configuration> </plugin> <plugin> <groupId>org.dstovall</groupId> <artifactId>onejar-maven-plugin</artifactId> <version>1.4.4</version> <executions> <execution> <configuration> </configuration> <goals> <goal>one-jar</goal> </goals> </execution> </executions> </plugin> </plugins> </build> <pluginRepositories> <pluginRepository> <id>onejar-maven-plugin.googlecode.com</id> <url>http://onejar-maven-plugin.googlecode.com/svn/mavenrepo</url> </pluginRepository> </pluginRepositories>
Then,
mvn clean package java -jar target/HelloWorld-1.0-SNAPSHOT.one-jar.jar