Spring:XML配置位置

时间:2015-05-13 20:21:04

标签: java xml spring spring-ioc

我是spring的学习者用spring IOC容器构建我的测试项目,并在我的项目根路径中配置beans.xml并加载到我的应用程序中并从中获取bean。

项目根目录中的spring.xml

BeanFactory bean = new XmlBeanFactory(new FileSystemResource("spring.xml"));

源文件中的spring.xml

BeanFactory bean = new XmlBeanFactory(new FileSystemResource("src/spring.xml"));

这是加载beans.xml文件的另一个代码

ApplicationContext context = new GenericXmlApplicationContext("beans.xml");

我的问题是,是否有任何标准或约定用于在实际项目中创建xml文件名和文件位置。因为在一些阅读文章中我还发现可能有多个xml文件用于大型项目,如service.xml和dao.xml。

1 个答案:

答案 0 :(得分:1)

让bean定义跨越多个XML文件会很有用。通常,每个单独的XML配置文件都代表一个逻辑层,例如在架构中定义DAO bean等,但是您应该始终将XML配置文件放在src / resources下并以

的形式访问它们。
new ClassPathXmlApplicationContext(new String[] {"services.xml", "daos.xml"});

从春季手册:

  

您可以使用应用程序上下文构造函数从所有这些XML片段加载bean定义。此构造函数采用多个Resource位置,如上一节中所示。或者,使用一个或多个元素来从另一个或多个文件加载bean定义。例如:

<beans>
  <import resource="services.xml"/>
  <import resource="resources/messageSource.xml"/>
  <import resource="/resources/themeSource.xml"/>

</beans>