# 10.2.4　使用嵌入式的数据源

除此之外，还有一个数据源是我想对读者介绍的：嵌入式数据库（embedded database）。嵌入式数据库作为应用的一部分运行，而不是应用连接的独立数据库服务器。尽管在生产环境的设置中，它并没有太大的用处，但是对于开发和测试来讲，嵌入式数据库都是很好的可选方案。这是因为每次重启应用或运行测试的时候，都能够重新填充测试数据。

Spring 的 jdbc 命名空间能够简化嵌入式数据库的配置。例如，如下的程序清单展现了如何使用 jdbc 命名空间来配置嵌入式的 H2 数据库，它会预先加载一组测试数据。

{% code title="程序清单 10.1 使用 jdbc 命名空间配置嵌入式数据库" %}

```markup
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:c="http://www.springframework.org/schema/c"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xsi:schemaLocation="http://www.springframework.org/schema/jdbc
	    http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
		http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans.xsd">
  ...
  
  <jdbc:embedded-database id="dataSource" type="H2">
    <jdbc:script location="classpath:spittr/db/jdbc/schema.sql" />
    <jdbc:script location="classpath:spittr/db/jdbc/test-data.sql" />
  </jdbc:embedded-database>
  
  ... 
  
</beans>
```

{% endcode %}

我们将 `<jdbc:embedded-database>` 的 type 属性设置为 H2，表明嵌入式数据库应该是 H2 数据库（要确保 H2 位于应用的类路径下）。另外，我们还可以将 type 设置为 DERBY，以使用嵌入式的 Apache Derby 数据库。

在 `<jdbc:embedded-database>` 中，我们可以不配置也可以配置多个 `<jdbc:script>` 元素来搭建数据库。程序清单 10.1 中包含了两个 `<jdbc:script>` 元素：第一个引用了 schema.sql，它包含了在数据库中创建表的 SQL；第二个引用了 test-data.sql，用来将测试数据填充到数据库中。

除了搭建嵌入式数据库以外，`<jdbc:embedded-database>` 元素还会暴露一个数据源，我们可以像使用其他的数据源那样来使用它。在这里，id 属性被设置成了 dataSource，这也是所暴露数据源的 bean ID。因此，当我们需要 javax.sql.DataSource 的时候，就可以注入 dataSource bean。

如果使用 Java 来配置嵌入式数据库时，不会像 jdbc 命名空间那么简便，我们可以使用 EmbeddedDatabaseBuilder 来构建 DataSource：

```java
@Bean
public DataSource dataSource() {
  return new EmbeddedDatabaseBuilder()
    .setType(EmbeddedDatabaseType.H2)
    .setScript("classpath:schema.sql")
    .setScript("classpath:text-data.sql")
    .build();
}
```

可以看到，setType() 方法等同于 `<jdbc:embedded-database>` 元素中的 type 属性，此外，我们这里用 addScript() 代替 `<jdbc:script>` 元素来指定初始化 SQL。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://potoyang.gitbook.io/spring-in-action-v4/untitled-4/untitled-2/untitled-1.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
