XML 作为外部配置 DSL
基于 XML 的配置元数据将这些 bean 配置为顶级
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">
1
id 属性是一个字符串,用于标识单个 bean 定义。
2
class 属性定义了 bean 的类型,使用完全限定类名。
id 属性的值可用于引用协作对象。本示例未展示引用协作对象的 XML。有关更多信息,请参阅依赖。
为了实例化容器,需要向 ClassPathXmlApplicationContext 构造函数提供 XML 资源文件的位置路径或多个路径,该构造函数允许容器从各种外部资源(例如本地文件系统、Java CLASSPATH 等)加载配置元数据。
Java
Kotlin
ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");
val context = ClassPathXmlApplicationContext("services.xml", "daos.xml")
学习 Spring 的 IoC 容器后,您可能想了解更多关于 Spring 的 Resource 抽象(如资源中所述)的信息,它提供了一种方便的机制,可以从 URI 语法定义的位置读取 InputStream。特别是,Resource 路径用于构建应用上下文,如应用上下文和资源路径中所述。
以下示例展示了服务层对象 (services.xml) 配置文件
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">
以下示例展示了数据访问对象 daos.xml 文件
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"> class="org.springframework.samples.jpetstore.dao.jpa.JpaAccountDao">
在前面的示例中,服务层由 PetStoreServiceImpl 类和两个数据访问对象组成,类型分别为 JpaAccountDao 和 JpaItemDao(基于 JPA 对象关系映射标准)。property name 元素引用 JavaBean 属性的名称,ref 元素引用另一个 bean 定义的名称。id 和 ref 元素之间的这种关联表达了协作对象之间的依赖关系。有关配置对象依赖项的详细信息,请参阅依赖。