Dipendency injection in spring example

1.create a java project.In source folder create a package.Inside  the package create the classes.Inside the source folder directly create an xml file named applicationContext.xml.


2.Load the spring jar files in the java build path.

---
code for setter injection in spring
-----------------------------------
Employee.java
-------------------------------------------
package com.sandeep.SpringPractice;

public class Employee {
private String name;
private int id;
private String location;


/*public Employee()
{
System.out.println("Inside default constructor");
}

public Employee(String name,int id,String location)
{
this.name=name;
this.id=id;
this.location=location;
}*/

public void setName(String name) {
this.name = name;
}


public void setId(int id) {
this.id = id;
}


public void setLocation(String location) {
this.location = location;
}


public String toString()
{
return ("name :"+name+"id is :"+id+"and location is :"+location);
}
}


-----------------------------------------------------------------------------
applicationContext.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" 
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- Define your beans here -->
  
    
     <bean id="e1" class="com.sandeep.SpringPractice.Employee" >
    <property name="name" value="sandeep"/>
    <property name="id" value="123"/>
    <property name="location" value="Odisha" />
    </bean>
    
          
</beans>



--------------------------------
MainApp.java
----------------------------------------
package com.sandeep.SpringPractice;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {

public static void main(String[] args) {

ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext
("applicationContext.xml");
Employee e1=context.getBean("e1",Employee.class);
System.out.println(e1);

}


}

--------------------------------------------
execute the file, MainApp.java
--------------------------------------------
output
---------------------------------
name :sandeepid is :123and location is :Odisha

Comments

Popular posts from this blog

Git Commands With Output Log

Java Interview Preparation (conceptual)

Java 8 Function Interface