Spring Project with Eclipse & Maven
1. Set up a Maven Project
GroupId identifies the project uniquely across all projects, so we need to provide a naming schema.
ArtifactId is the name of the jar without version.
2. Add Spring Dependency
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>com.devyan</groupId>
<artifactId>DependencyInjectionByConstructor</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies>
<properties>
<spring.version>3.2.3.RELEASE</spring.version>
</properties>
</project>
3. Create the Spring Bean Configuration File
Create a bean configuation file named "applicationContext.xml" under src/main/resources directory.
<?xml version="1.0"
encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="e"
class="com.devyan.Employee">
<constructor-arg value="10" type="int"
></constructor-arg>
<constructor-arg value="Devayan"></constructor-arg>
</bean>
</beans>
4. Create a Spring Bean
Create Employee Bean under /src/main/java directory.
package com.devyan;
public class Employee {
private int id;
private String name;
public Employee()
{
System.out.println("def cons");
}
public Employee(int d)
{
this.id=id;
}
public Employee(String name) {
this.name=name;
}
public Employee(int id,String name) {
this.id=id;
this.name=name;
}
void show() {
System.out.println("ID:"+id+" "+"Name:"+name);
}
}
5. Run the Maven Project
Create a Test class under /src/main/java directory to test the project.
package
com.devyan;
import
org.springframework.beans.factory.BeanFactory;
import
org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.*;
public class
Test {
public static void
main(String[] args) {
ApplicationContext context=new
ClassPathXmlApplicationContext(new
String[]{"applicationContext.xml"});
BeanFactory factory=context;
Employee
s=(Employee)factory.getBean("e");
s.show();
}
}
OUTPUT:
ID:10 Name:Devayan
Awesome
ReplyDeletesupercalifragilisticexpialidocious ✌️
ReplyDeleteInformative post
ReplyDelete