<alias> in Spring XML

By Arvind Rai, November 02, 2021
Spring <alias> element defines an alias for a bean in XML configuration. The <alias> element can be used to alias a bean outside the bean definition. The <alias> is useful in the large applications where configurations are split amongst each subsystem and each subsystem is having its own bean definitions. If we wish to introduce an alias for a bean that is defined elsewhere, we can use <alias> element in XML configuration.
Find the code to use <alias> element.
<alias name="ent" alias="alias_ent"/> 

<alias> Example

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.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.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());
    } 
} 

Reference

Aliasing a Bean outside the Bean Definition
POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us