Dependency Example in spring

We use Dependency Injection (DI) to implement loose coupling.
Every time you create an instance of a class by using the new keyword,
You tightly couple your code to that class.

You can inject dependency in constructor or in setter method.

Project Structure

Employee.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package org.training.javaforlearn;
 
public class Employee 
{
 
	String emp_name;
 
	//getter method
	public String getEmp_name()
	{
		return emp_name;
	}
 
      //setter method
	public void setEmp_name(String emp_name) 
	{
		this.emp_name = emp_name;
	}
 
}

Spring-config.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?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="emp" class="org.training.javaforlearn.Employee">  
 
<property name="emp_name"  value="Bhavesh"/>
 
</bean>
 
 
</beans>

TestMain.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package org.training.javaforlearn;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class TestMain 
{
 
	public static void main(String[] args)
	{	
        	   System.out.println("**********************");	
                  ApplicationContext context=new ClassPathXmlApplicationContext("Spring-config.xml");	
                   Employee e=	(Employee)context.getBean("emp");
	    String name= e.getEmp_name();
	    System.out.println("Hello: "+name);
	    System.out.println("***********************");
	}
}

Output

Leave a Reply

Your email address will not be published. Required fields are marked *