Home  >  Spring Core

Example of alias in Spring

By Arvind Rai, April 08, 2013
In Spring bean we can define alias of bean itself. We can keep more than one name of the same bean. Usability of alias is in the case where application is too large and we want loose coupling of even bean names among each other. We use alias as below.
<alias name="ent" alias="alias_ent"/>
 
Find the sample example of alias.
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">
       <property name="name" value="Entitlement"/>
       <property name="time" value="50"/>
    </bean>
    <alias name="ent" alias="alias_ent"/>
</beans> 

Entitlement.java
package com.concretepage;
public class Entitlement {
	private String name;
	private int time;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getTime() {
		return time;
	}
	public void setTime(int time) {
		this.time = time;
	}
}  
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("alias_ent");
        System.out.println(ent.getName());
        System.out.println(ent.getTime());
    } 
} 
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS


©2019 concretepage.com | Privacy Policy | Contact Us