Monday, 19 August 2013

Sample Spring Example with Maven(POM)

Example uses Maven to generate a simple Java project structure, and demonstrates how to retrieve Spring bean and prints a “hello ! ” string.

Goto Eclipse IDE  File->New->Others->MavenProject


Click on next



 Group Id and Artifact Id must be project name

Project Structure: Make sure the folder structure as follows:


 pom.xml:

<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>Sample-Maven</groupId>
  <artifactId>Sample-Maven</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
  <dependencies>
 
  <!-- Spring framework -->
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring</artifactId>
   <version>2.5.6</version>
  </dependency>
 
 </dependencies>
 
</project> 
 
HelloWorld.java
package com.alekhya.common; public class HelloWorld { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public void printHello() { System.out.println("Hello ! " + name); } }
 
Spring-Module.xml:
<?xml version="1.0" encoding="UTF-8"?>
<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="com.alekhya.common.HelloWorld">
  <property name="name" value="Alekhya" />
 </bean>
 
</beans>
 App.java:
package com.alekhya.common; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class App { public static void main(String[] args) { ApplicationContext context=new ClassPathXmlApplicationContext("Spring-Module.xml"); HelloWorld obj=(HelloWorld)context.getBean("helloBean"); obj.printHello(); } }
 
Run it:Output
 
Hello ! Alekhya
 
 
 


1 comment:

Unknown said...

please provide more information about maven projects.This is basic example is very helpful for beginners.