【Spring】别名设置

一:为什么使用别名?

    通过这样的别名配置,可以达到在一个地方命名,在多个地方使用不同的名字和效果。


二:什么是别名?

    其实就是它的另外的名字,例如你的小名,昵称等。


三:怎样做?

    首先先要看上完篇写的博客:【Spring】IOC控制反转-demo

然后对其稍微修改一下即可:


在applicationContext.xml中设置别名:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

	<!-- 
		把HelloWorld这个类 纳入spring容器中
		id为bean的唯一标识
			正规写法:
				类的第一个字母变成小写,其余不变
		class为类的全名			
	 -->
	 <bean id="helloWorld" class="cn.itcast.springtest.ioc.HelloWorld"></bean>
	 <alias alias="牛大千" name="helloWorld"></alias>  //别名的设置
	 <alias alias="大千" name="helloWorld"></alias>
</beans>

在IOCTest.java中启动spring容器:

这里面可以将helloWorld改为你设置的别名

/*
 * 控制反转IOC
 * 牛千千
 */
public class IOCTest {
	/*
	 * 启动spring容器
	 * 		创建spring容器对象就相当于启动了spring容器
	 */
	@Test
	public void testHelloWorld(){
		ApplicationContext context =new ClassPathXmlApplicationContext("cn/itcast/springtest/ioc/applicationContext.xml");
		HelloWorld helloWorld = (HelloWorld)context.getBean("helloWorld"); //这里可以写成设置的别名:牛大千、大千
		helloWorld.say();
	}
	
}


猜你喜欢

转载自blog.csdn.net/n950814abc/article/details/79967066