目录
1.1. Introduction to the Spring IoC Container and Beans
1.2.2. Instantiating a Container
1.1. Introduction to the Spring IoC Container and Beans
IOC容器的必要包是
org.springframework.beans
org.springframework.context
The BeanFactory interface provides an advanced configuration mechanism capable of managing any type of object.
BeanFactory接口提供能管理任何对象类型的高级配置机制。
Mechanism ['mekə.nɪzəm]
ApplicationContext 是 BeanFactory的一个完整子集,增加了
- 更易于集成AOP的特性
- 信息资源处理
- 事件发布
- 应用程序层特定上下文(比如WebApplicationContext用于web应用)
BeanFactory提供了配置框架和基本功能。ApplicationContext则增加了更多企业特定的功能。
Beans定义
In Spring, the object that form the backbone of your application and that are managed by the Spring IoC container are called beans.
在Spring中,构成应用程序主干并由Spring IoC容器管理的对象称为bean。
A bean is an object that is instantiated, assembled and otherwise managed by a Spring IoC container.
bean是由Spring IoC容器实例化、组装和以其他方式管理的对象。
Otherwise, a bean is simple one of many object of your application. Bean, and the dependencies among them, are reflected in configuration metadata used by container.
换句话说,bean是程序中众多对象中的一个简单对象。bean及其之间的依赖关系会反映在容器使用的配置元数据中。
1.2. Container Overview
ApplicationContext
Application 接口表示Spring IoC容器,负责实例化、配置和组装beans。
The container get its instructions on what objects to instantiate, configure, and assemble by reading configuration metadata.
容器通过读取配置元数据来获取实例、配置和组装哪些对象的指令。
The configuration metadata is represented in XML, java annotations or java code.
配置元数据使用xml,java注解或者Java代码表示。
一些ApplicationContext接口的实现由Spring提供。在独立应用程序中,通常要创建ClassPathXmlApplicationContext或者FileSystemXmlApplication的实例。
While XML has been the traditional format for defining configuration metadata, you can instruct the container to use Java annotations or code as the metadata format by providing a small amount of XML configuration to declaratively enable support for these additional metadata formats.
虽然XML一直是定义配置元数据的传统格式,但是可以通过提供少量XML配置以声明方式支持这些额外的元数据格式,从而指示容器使用Java注释或代码作为元数据格式。
八行模板代码
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/daoContext.xml /WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
1.2.1. Configuration Metadata
除了使用xml方式作为配置元数据外,还有其他的方式:
- Annotation-based configuration(Spring 2.5)
- Java-based configuration(Spring 3.0): Spring Javaconfig提供了很多新的特性,并且成为Spring framework的一部分
细粒度
细粒度模型,通俗的讲就是将业务模型中的对象加以细分,从而得到更科学合理的对象模型,直观的说就是划分出很多对象.
所谓细粒度的划分就是在pojo类上的面向对象的划分,而不是在于表的划分上 例如:在三层结构中持久化层里面只做单纯的数据库操作
粗粒度和细粒度的区别主要是出于重用的目的,像类的设计,为尽可能重用,所以采用细粒度的设计模式,将一个复杂的类(粗粒度)拆分成高度重用的职责清晰的类(细粒度).对于数据库的设计,原责:尽量减少表的数量与表与表之间的连接,能够设计成一个表的情况就不需要细分,所以可考虑使用粗粒度的设计方式.
The following example shows the basic structure of XML-based configuration metadata:
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="..." class="...">
<!-- collaborators and configuration for this bean go here -->
</bean>
<bean id="..." class="...">
<!-- collaborators and configuration for this bean go here -->
</bean>
<!-- more bean definitions go here -->
</beans>
The id attribute is a string that identifies the individual bean definition.
id属性是一个bean定义的唯一标识的字符串。
The class attribute defines the type of bean and use the fully qualified classname.
class属性定义了bean的类型和类全路径名称
The value of the id attritue refers to collaborating object. id属性的值作为协作对象的引用。
1.2.2. Instantiating a Container
ApplicationContext的构造方法的位置路径是资源字符串,可以让容器在一些外部资源中(比如本地文件系统,java类路径等等)获取配置元数据。
类路径获取配置元数据的方式:
ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");
资源路径用于构造应用程序的上下文
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
https://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
https://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>
The property name element refers to the name of JavaBean property, and the ref element refers to the name of another bean definition.
The linkage between id and ref elements expresses the dependency between collaborating objects.
name元素引用JavaBean属性的名称。
ref元素引用另一个bean定义的名称。
id和ref元素这种链接关系表达了协作对象之间的依赖关系。
Composing XML-based Configuration Metadata
一般来说,让bean跨多个xml文件是有意义的,因为每个单独的xml文件都对应着体系结构的某个逻辑层或者模块。我们可以使用<import/>
引入其他的xml文件中的bean。
像这样:
<beans>
<import resource="services.xml"/>
<import resource="resources/messageSource.xml"/>
<import resource="/resources/themeSource.xml"/> <!-- 这个是绝对路径嗷 -->
<bean id="bean1" class="..."/>
<bean id="bean2" class="..."/>
</beans>
All location paths are relative to the definition file doing the importing.
所有路径位置都相对于执行导入的文件。
正如我们看到了,/resources/themeSource.xml 首个斜杠被忽略了,最好就不要加这个斜杠。
根据Spring Schema,导入的文件内容(包括beans)必须是有效的XML bean定义。
另外,不推荐使用 '../' 来寻找父级目录。因为这样做会在当前应用程序外面创建一个外部文件的依赖。特别是不建议在classpath的URLS中使用 '../' 这玩意。因为程序在解析时会选择最近的“classpath”根路径。????存疑
该文章讲述了什么是classpath classpath和jar
The Groovy Bean Definition DSL
可以使用外部化的配置元数据定义bean。例如使用Spring的Groovy Bean Definition DSL来外部定义。
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配置命名空间。它也同样能通过
importBeans
指令导入XML bean定义文件。
1.2.3. Using the Container
The ApplicationContext is the interface for an advanced factory capable of maintaining a registry of different beans and their dependencies.
ApplicationContext 是维护不同bean和及其依赖项的注册表的高级工厂接口。
By using the method T getBean(String name, Class<T> requiredType)
, you can retrieve instances of your beans.
使用getBean方法,可以检索bean的实例
// create and configure beans
ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");
// retrieve configured instance
PetStoreService service = context.getBean("petStore", PetStoreService.class);
// use configured instance
List<String> userList = service.getUsernameList();
使用Groovy配置的方式也十分相似。
ApplicationContext context = new GenericGroovyApplicationContext("services.groovy", "daos.groovy");
另外,也可以十分灵活的使用GenericApplicationContext
与reader委托结合的方式获取bean。
GenericApplicationContext context = new GenericApplicationContext();
new XmlBeanDefinitionReader(context).loadBeanDefinitions("services.xml", "daos.xml");
context.refresh();
当然,也可以把 XmlBeanDefinitionReader替换为GroovyBeanDefinitionReader.
GenericApplicationContext context = new GenericApplicationContext();
new GroovyBeanDefinitionReader(context).loadBeanDefinitions("services.groovy", "daos.groovy");
context.refresh();
ApplicationContext
还有一些方法能获取到bean。但在实际开发中,我们不会使用这种方法来获取bean,以免与Spring API耦合。Spring 与web框架集成为各种web框架组件提供了依赖注入,可以通过元数据(如自动装配注解)声明对一些特定bean的依赖项。
原文如下:
For example, Spring’s integration with web frameworks provides dependency injection for various web framework components such as controllers and JSF-managed beans, letting you declare a dependency on a specific bean through metadata (such as an autowiring annotation).