Spring_02_配置文件_import和name

前文:Spring_概述与Hello world

import

为方便管理配置文件,推荐使用import来规划配置文件。

在applicationContext.xml中,通过配置<import>的resource来导入配置文件。

1、默认情况下,是使用相对路径来寻找配置文件。

(相对于applicationContext.xml)

2、Spring提供了前缀标记用于辅助查找配置文件。

[file:]:使用文件系统的路径方式查找。

[classpath:]:从classpath后查找。推荐使用该方式。

  • 演示

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.xsd">
    
   <import resource="classpath:com/hanaii/hello/hello.xml"/>
    
</beans>

hello.xml

扫描二维码关注公众号,回复: 3081003 查看本文章
<?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.xsd">
    <bean id="hello" class="com.hanaii.hello.Hello" />
</beans>

name

Spring配置文件中,要求<bean>中的id属性值是唯一的。

若bean需要其他的名字,可以配置name属性。

1、name属性可通过逗号、分号、空格来分割多个名字。

2、可通过BeanFactory的getAlias方法获取一个bean的所有名字。

3、一般使用id即可。在SpringMVC,可在name中配置多个名字来代表映射的URL地址。

猜你喜欢

转载自blog.csdn.net/hanaii/article/details/82425380