Monday, May 13, 2013

Spring - Constructor Injection

In Spring IoC (Inversion of Control), there are two sorts of Dependency Injection -
  1. Setter Injection
  2. Constructor Injection
Setter Injection is implemented by <property> and Constructor Injection is implemented by <constructor-arg>.

Snip of spring.xml -

    
    

 

    

    

    

    

    
    


Snip of App code -
        ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
        Student student = (Student) context.getBean("student");
        Student student2 = (Student) context.getBean("student2");
        Student student3 = (Student) context.getBean("student3");
        Student student4 = (Student) context.getBean("student4");
        student.display();
        student2.display();
        student3.display();
        student4.display();

Output -
Name is: Tom, and ID is: 1
Name is: null, and ID is: 2
Name is: Jerry, and ID is: 0
Name is: Micky, and ID is: 3

No comments:

Post a Comment