Home  >  Spring Core

Example of constructor-arg in Spring

By Arvind Rai, April 01, 2013
In spring when bean is initialized as constructor-arg then dependency can be injected by name, type or index. Here we will understand how to inject dependency by constructor argument as index. index attribute is used with property tag.

spring-config.xml
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
     
    <bean id="ent" class="com.concretepage.Entitlement">
       <constructor-arg index="0" value="Index Demo"/>
       <constructor-arg index="1" value="200"/>
    </bean>
    
  </beans>
 





SpringDemo.java
package com.concretepage;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringDemo {
    public static void main(String... args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
        
        Entitlement ent=(Entitlement)context.getBean("ent");
        System.out.println(ent.getName());
        System.out.println(ent.getTime());
    } 
}
 


Entitlement.java
package com.concretepage;
public class Entitlement {
	private String name;
	private int time;
	public Entitlement(String name,int time){
		this.name=name;
		this.time=time;
	} 
	public String getName() {
		return name;
	}
	public int getTime() {
		return time;
	}
}
  
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us