微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

IOC配置文件的加载

2 IOC配置文件的加载

2.1 单配置文件的加载

spring.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
    https://www.springframework.org/schema/beans/spring-beans.xsd">
 
  <bean id="userService" class="com.xxxx.service.UserService"></bean>
</beans>

根据相对路径加载:

ApplicationContext ac  = new ClasspathXmlApplicationContext("spring.xml");

2.2 多配置文件加载

service.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
    https://www.springframework.org/schema/beans/spring-beans.xsd">
 
  <bean id="userService" class="com.xxxx.service.UserService"></bean>
</beans>

dao.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
    https://www.springframework.org/schema/beans/spring-beans.xsd">
 
  <bean id="userDao" class="com.xxxx.dao.UserDao"></bean>
</beans>
// 同时加载多个资源文件
ApplicationContext ac = new
ClasspathXmlApplicationContext("spring.xml","dao.xml");

通过总的配置文件import其他配置文件:

spring.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
    https://www.springframework.org/schema/beans/spring-beans.xsd">
 
  <!--导入需要包含的资源文件-->
  <import resource="service.xml"/>
  <import resource="dao.xml"/>
</beans>

加载时只需加载总的配置文件即可:

// 加载总的资源文件
ApplicationContext ac = new ClasspathXmlApplicationContext("spring.xml");

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。