java - Spring : XML Configuration Location

标签 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。

最佳答案

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

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

摘自 Spring 手册:

You can use the application context constructor to load bean definitions from all these XML fragments. This constructor takes multiple Resource locations, as was shown in the previous section. Alternatively, use one or more occurrences of the element to load bean definitions from another file or files. For example:

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

</beans>

关于java - Spring : XML Configuration Location,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30224485/

相关文章:

java - Spring FileSystemResource NoSuchFileException

java - 使用 Java DOM 解析器对 XML 输出进行标记 - 多个子节点值

java - 没有 xsd 的 Spring WS

java - 访问 JAX RS CXF Web 服务时没有这样的方法错误

java - 自定义注释初始化方法不起作用

java - 我将如何创建 "infinite"循环,直到用户决定退出?

java - 将 "AES"指定为 KeyGenerator.getInstance() 中的算法究竟有什么作用?

android - 如何使用存储在 xml 中的可绘制数组使用 ImageAdapter 填充 gridView

php - 在 php 中通过 post 接收 xml 文件

java - 在 Spring 中验证每个请求和响应的用户