【Spring】別名設定
阿新 • • 發佈:2019-01-22
一:為什麼使用別名?
通過這樣的別名配置,可以達到在一個地方命名,在多個地方使用不同的名字和效果。
二:什麼是別名?
其實就是它的另外的名字,例如你的小名,暱稱等。
三:怎樣做?
然後對其稍微修改一下即可:
在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();
}
}