多个 Spring 配置文件
在实际应用里,随着应用规模的增加,系统中 Bean 数量也大量增加,导致配置文件变 得非常庞大、臃肿。为了避免这种情况的产生,提高配置文件的可读性与可维护性,可以将 Spring 配置文件分解成多个配置文件。方式一: 在resources目录下创建多个spring配置文件:
spring-aop.xml
spring-bean.xml
然后在测试方法中使用下面方式即可:
String[] files = {"spring-aop.xml","spring-bean.xml","applicationContext.xml"};
ApplicationContext context = new ClassPathXmlApplicationContext(files);
将配置文件写到数组中,然后将数组作为参数传入ClassPathXmlApplicationContext中。
方式二
在applicationContext.xml配置文件中加入下面内容,此时applicationContext.xml相当于是父配置文件:
也可以使用下面这种方式,使用*号作为通配符,需要注意该方式的父配置文件的名称中不能是spring-开头,否则会无限递归:
在测试方法中直接使用下面方式即可:
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");