Spring 容器的实例化 1.2.2. Instantiating a container
Instantiating a Spring IoC container is straightforward. The location path or paths supplied to an ApplicationContext constructor are actually resource strings that allow the container to load configuration metadata from a variety of external resources such as the local file system, from the Java CLASSPATH, and so on.
实例化一个spring ioc容器是很直接了当的。只要给ApplicationContext的构造器提供配置文件的路径即可。配置文件可以拥有多种形式,可以基于xml,也可以基于Groovy 语言的形式,也可以从本地文件系统中的CLASSPTH路径下加载。实例化代码如下:
ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");
After you learn about Spring’s IoC container, you may want to know more about Spring’s Resource abstraction, as described in Resources, which provides a convenient mechanism for reading an InputStream from locations defined in a URI syntax. In particular, Resource paths are used to construct applications contexts as described in Application contexts and Resource paths.
spring 的 Resources提供了一种方便的机制来从一个URL形式的地址中获取一个输入流。在Application context2 And Resource paths的章节中Resource 的路径方式被用来构造应用程序的上下文。
The following example shows the service layer objects (services.xml) configuration file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- services -->
<bean id="petStore" class="org.springframework.samples.jpetstore.services.PetStoreServiceImpl">
<property name="accountDao" ref="accountDao"/>
<property name="itemDao" ref="itemDao"/>
<!-- additional collaborators and configuration for this bean go here -->
</bean>
<!-- more bean definitions for services go here -->
</beans>
The following example shows the data access objects daos.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="accountDao"
class="org.springframework.samples.jpetstore.dao.jpa.JpaAccountDao">
<!-- additional collaborators and configuration for this bean go here -->
</bean>
<bean id="itemDao" class="org.springframework.samples.jpetstore.dao.jpa.JpaItemDao">
<!-- additional collaborators and configuration for this bean go here -->
</bean>
<!-- more bean definitions for data access objects go here -->
</beans>
In the preceding example, the service layer consists of the class PetStoreServiceImpl
, and two data access objects of the type JpaAccountDao
and JpaItemDao
(based on the JPA Object/Relational mapping standard). The property name element refers to the name of the JavaBean property, and the ref element refers to the name of another bean definition. This linkage between id and ref elements expresses the dependency between collaborating objects. For details of configuring an object’s dependencies, see Dependencies.
以上的例子中,service层的PetStoreServiceImpl类引用了两个dao层的类JpaAccountDao、JpaItemDao。属性名代表的是javaBean中对应的属性名,ref元素指向它需要的另一个bean类的定义。
Composing XML-based configuration metadata
将配置文件进行组合
It can be useful to have bean definitions span multiple XML files. Often each individual XML configuration file represents a logical layer or module in your architecture.
将配置文件的定义分为几个xml文件是很有用的。通常每个单独的xml配置文件在你的应用构造中代表一个逻辑层或模型
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:
你可以使用如下的方式通过传入多个资源路径的形式来构造应用的上下文
ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");
你也可以使用如下资源整合的方式来构造应用的上下文
<beans>
<import resource="services.xml"/>
<import resource="resources/messageSource.xml"/>
<import resource="/resources/themeSource.xml"/>
<bean id="bean1" class="..."/>
<bean id="bean2" class="..."/>
</beans>
In the preceding example, external bean definitions are loaded from three files: services.xml, messageSource.xml, and themeSource.xml. All location paths are relative to the definition file doing the importing, so services.xml must be in the same directory or classpath location as the file doing the importing, while messageSource.xml and themeSource.xml must be in a resources location below the location of the importing file. As you can see, a leading slash is ignored, but given that these paths are relative, it is better form not to use the slash at all. The contents of the files being imported, including the top level element, must be valid XML bean definitions according to the Spring Schema.
在之前的例子中,外部bean的定义从service.xml、messageSource.xml、themeSource.xml 三个文件中加载。所有的位置路径都是相对于这个整合的xml文件的,所以service.xml文件必须和这个整合的xml文件在同一个目录或类路径地址下,而messageSource.xml、themeSource.xml文件必须在整合xml文件地址下的一个resource目录下。正如你看到的,/resources/themeSource.xml
的反斜杠被忽略了,但是鉴于这些路径是相对的,最好不要使用反斜杠。另外被import进来的xml文件必须满足spring xml 的定义
It is possible, but not recommended, to reference files in parent directories using a relative “../” path. Doing so creates a dependency on a file that is outside the current application. In particular, this reference is not recommended for “classpath:” URLs (for example, “classpath:../services.xml”), where the runtime resolution process chooses the “nearest” classpath root and then looks into its parent directory. Classpath configuration changes may lead to the choice of a different, incorrect directory.
如果可能,但是不推荐使用”../”路劲来指向上一级目录下的文件。这样做会创建在应用程序之外的依赖关系。这种引用方式尤其不推荐使用在”classpath:”的URL中(举个例子,”classpath:../services.xml”)。因为运行时解析程序会选则最近的类路径根目录,然后再查找它的父目录。Classpath的配置的改变可能会导致进入一个不同的,不正确的目录。
You can always use fully qualified resource locations instead of relative paths: for example, “file:C:/config/services.xml” or “classpath:/config/services.xml”. However, be aware that you are coupling your application’s configuration to specific absolute locations. It is generally preferable to keep an indirection for such absolute locations, for example, through “${…}” placeholders that are resolved against JVM system properties at runtime.
你完全可以使用全路径的方式来指向资源文件,例如”file:C:/config/services.xml” or “classpath:/config/services.xml”。但是,一定要意识到,你将你应用的配置耦合到了一个确定的地址下。通常,我们对于这样的绝对地址,举个例子,我们会使用通过在JVM系统运行时的属性解析的${…}占位符。反正从解耦合的角度来讲,不推荐使用绝对路径
The import directive is a feature provided by the beans namespace itself. Further configuration features beyond plain bean definitions are available in a selection of XML namespaces provided by Spring, e.g. the “context” and the “util” namespace.
import导入指令是beans 命名空间提供的功能。除了普通bean定义外的更多的配置在spring 提供的context和util命名空间中
The Groovy Bean Definition DSL
As a further example for externalized configuration metadata, bean definitions can also be expressed in Spring’s Groovy Bean Definition DSL, as known from the Grails framework. Typically, such configuration will live in a “.groovy” file with a structure as follows:
bean的定义还可以通过spring的DSL,这种方式在Grails的框架使用中国而出名。具体格式如下
beans {
dataSource(BasicDataSource) {
driverClassName = "org.hsqldb.jdbcDriver"
url = "jdbc:hsqldb:mem:grailsDB"
username = "sa"
password = ""
settings = [mynew:"setting"]
}
sessionFactory(SessionFactory) {
dataSource = dataSource
}
myService(MyService) {
nestedBean = { AnotherBean bean ->
dataSource = dataSource
}
}
}
This configuration style is largely equivalent to XML bean definitions and even supports Spring’s XML configuration namespaces. It also allows for importing XML bean definition files through an “importBeans” directive.
这种配置形式和xml中bean的定义大致是相同的,它甚至还支持spring xml 配置的命名空间。它还允许导入xml bean的定义文件通过一个importBeans指令