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");
上一篇:安卓 ADB常见问题整理


下一篇:PAT A 1080 AC代码