🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
**1. 拆分Spring配置文件的目的** (1)项目规模大,配置文件的可读性、维护性差。 (2)团队开发,多人修改同一个配置文件,易发生冲突。 <br/> **2. 拆分策略有两种** (1)公用配置 + 每个系统模块单独一个配置文件(DAO + Service + Web控制器),适用于多人开发的团队。 :-: ![](https://img.kancloud.cn/1b/d1/1bd1478407e0fbfe0fb1cf0b94077d41_386x364.png) (2)公用配置 + DAO层的Bean配置 + Service层的Bean配置 + Web控制器层的Bean配置,适用于个人开发或少数人团队开发。 :-: ![](https://img.kancloud.cn/b3/87/b3879d27c38a9ebe8593ce8dda204476_328x273.png) <br/> **3. 配置文件拆分演示** 下面演示第2种拆分策略,步骤如下: (1)将一些公共配置放在`ApplicationContext.xml`文件中,如数据源、事务管理等。 ```xml <?xml version="1.0" encoding="UTF-8"?> <beans ...> <!-- 配置数据源 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&amp;characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value="admin"/> </bean> <!-- 创建sqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!-- 注入mapper.xml --> <property name="mapperLocations"> <list> <value>classpath:mapper/StudentMapper.xml</value> </list> </property> </bean> </beans> ``` (2)将dao层配置放在`ApplicationContext-dao.xml`文件中。 ```xml <?xml version="1.0" encoding="UTF-8"?> <beans ...> <!-- 创建dao层--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 该配置会将dao层下的所有xxxMapper接口注入到basePackage中 --> <property name="basePackage" value="dao"/> </bean> </beans> ``` (3)将service层的配置放在`ApplicationContext-service.xml`文件中。 ```xml <?xml version="1.0" encoding="UTF-8"?> <!-- default-autowire="byName"表示全局的Service采用按名字自动装配 --> <beans default-autowire="byName" ...> <!-- 创建service层 --> <bean id="studentService" class="service.imp.StudentServiceImpl"> <!--<property name="studentMapper" ref="studentMapper"/>--> </bean> </beans> ``` (4)将拆分的Spring配置文件合并。 合并方式一:使用`ClassPathXmlApplicationContext(String... configLocations)`将多个配置文件合并。 ```java @org.junit.Test public void test() { ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml" ,"ApplicationContext-dao.xml", "ApplicationContext-service.xml"); StudentService studentService = (StudentService) context.getBean("studentService"); } ``` 合并方式二:`<import resource="xxx.xml"/>`在一个配置文件中导入其它配置。 *`ApplicationContext.xml`* ```xml <import resource="ApplicationContext-dao.xml"/> <import resource="ApplicationContext-service.xml"/> ```