Spring Framework Reference 简记

引言

Spring框架已经是Java Web开发中必不可少的一部分,但是自己对Spring的模块、配置、规范都一知半解。因此,在项目开发中埋下了不少隐患。所以,从官方文档开始,尽力去了解整个Spring的内容,此文作为记录以及督促。

官方文档地址:http://docs.spring.io/spring/docs/current/spring-framework-reference/pdf/spring-framework-reference.pdf

2016年8月18日

Overview of the Spring Framework

1:Core Container

Core Container包括spring-core,spring-beans,spring-context,spring-context-support和spring-expressin(Spring Expression Language)模块。

spring-corespring-beans提供了Spring框架的基本功能,包括控制反转(IoC)和依赖注入(DI)。其中,BeanFactory是工厂模式久经考验的一种实现方式。

spring-context是建立在core和beans的基础之上的,提供框架风格的对象访问方式,类似JNDI注册。其中,ApplicationContext是context模块的核心。spring-context-support提供集成常用第三方类库的支持,包括缓存(EhCache,Guava,JCache),邮件(JavaMail),任务调度(CommonJ,Quartz)和模板引擎(FreeMarker,JasperReports,Velocity)。

spring-expression提供了Spring的表达式语言(Expression Langugae)。

2:AOP and Instrumentation

spring-aop模块提供面向切面编程的实现,允许定义方法拦截器和切点来解耦代码。

spring-aspects模块提供AspectJ的集成。

spring-instrument模块提供在类仪器支持和类加载器实现。

3:Messaging

spring-messaging模块是Spring Framework 4中引入的,提供了基于消息应用的基础功能,还提供了基于注解的消息映射。

4:Data Access/Integration

数据访问层包括JDBC,ORM,OXM,JMS和事务模块。

spring-jdbc

spring-tx

spring-orm

spring-oxm

spring-kms

5:Web

Web层是由spring-web,spring-webmvc,spring-websocket和spring-webmvc-portlet模块构成。

spring-web模块提供基本的面向Web的集成特性,包括文件续传和IoC容器的初始化。它还包含HTTP客户端和Web相关的Spring远程支持。

spring-webmvc模块包含网络应用的MVC和REST实现。

spring-webmvc-portlet

6:Test

spring-test通过JUnit或TestNG提供单元和集成测试功能,还提供mock测试。

Typical full-fledged Spring web application

Spring Framework Artifacts

GroupId ArtifactId Description
org.springframework spring-aop Proxy-based AOP support
org.springframework spring-aspects AspectJ based aspects
org.springframework spring-beans Beans support, includingGroovy
org.springframework spring-context Application context runtime,including scheduling andremoting abstractions
org.springframework spring-context-support Support classes for integratingcommon third-party librariesinto a Spring application context
org.springframework spring-core Core utilities, used by manyother Spring modules
org.springframework spring-expression Spring Expression Language(SpEL)
org.springframework spring-instrument In Instrumentation agent for JVMbootstrapping
org.springframework spring-instrument-tomcat Instrumentation agent forTomcat
org.springframework spring-jdbc JDBC support package,including DataSource setup andJDBC access support
org.springframework spring-jms JMS support package, includinghelper classes to send andreceive JMS messages
org.springframework spring-messaging S Support for messagingarchitectures and protocols
org.springframework spring-orm Object/Relational Mapping,including JPA and Hibernatesupport
org.springframework spring-oxm Object/XML Mapping
org.springframework spring-test Support for unit testing andintegration testing Springcomponents
org.springframework spring-tx Transaction infrastructure,including DAO support and JCAintegration
org.springframework spring-web Web support packages,including client and webremoting
org.springframework spring-webmvc REST Web Services andmodel-view-controllerimplementation for webapplications
org.springframework spring-webmvc-portlet MVC implementation to be usedin a Portlet environment
org.springframework spring-websocket WebSocket and SockJSimplementations, includingSTOMP support

物料单

可以在依赖管理中加入spring-framework-bom来确保所有Spring依赖保持在同一版本。

1
2
3
4
5
6
7
8
9
10
11
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-framework-bom</artifactId>
<version>4.3.2.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

通过导入以上配置,就不需要再特别指定版本属性。

1
2
3
4
5
6
7
8
9
10
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
</dependencies>

部分新特性:

@Order

@Lazy

@Description

@RestController

截止65/907页

2016年8月19日

The IoC container

org.springframework.beansorg.springframework.context是Spring框架IoC容器的基础。BeanFactory接口提供了一个先进的配置机制来管理任何类型的对象。ApplicationContext是BeanFactory的一个子接口,它可以更方便集成Spring的AOP特性。

在Spring中,用于构成应用骨架同时被Spring IoC容器管理的对象成为beans。

Container overview

接口org.springframework.context.ApplicationContext代表Spring IoC容器,同时负责实例化、配置和组装相关beans。容器通过配置信息来得知哪些对象需要实例化、配置或组装的指令。配置信息可以是XML、Java注解或者Java代码。

Spring提供ApplicationContext接口的多种开箱即用(out-of-the-box)实现方式。在单应用中,一般是创建ClassPathXmlApplicationContext或者FileSystemXmlApplicationContext实例。

TheSpringIoCContainer

下面是基于XML配置信息的例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
<?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="..." 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>

id是bean的唯一标识,class是定义bean的类型,要求包含包路径。

容器初始化代码:

ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"services.xml", "daos.xml"});

多文件XML配置

1
2
3
4
5
6
7
<beans>
<import resource="services.xml"/>
<import resource="resources/messageSource.xml"/>
<import resource="/resources/themeSource.xml"/>
<bean id="bean1" class="..."/>
<bean id="bean2" class="..."/>
</beans>

使用容器

1
2
3
4
5
6
7
// create and configure beans
ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"services.xml", "daos.xml"});
// retrieve configured instance
PetStoreService service = context.getBean("petStore", PetStoreService.class);
// use configured instance
List<String> userList = service.getUsernameList();

Bean overview

通过静态工厂方法实例化bean

1
<bean id="clientService" class="examples.ClientService" factory-method="createInstance"/>
1
2
3
4
5
6
7
public class ClientService {
private static ClientService clientService = new ClientService();
private ClientService() {}
public static ClientService createInstance() {
return clientService;
}
}

Dependencies

依赖注入有两种主要方式:基于构造方法的依赖注入(constructor-based DI),基于Setter方法的依赖注入(setter-based DI)。

依赖解决过程:

  • 创建ApplicationContext,同时通过配置信息描述所有bean,配置信息可以是XML、Java代码或者注解。
  • 对于每一个bean,它的依赖被表示成属性、构造参数或者静态方法的参数。当bean被实际创建的时候提供给bean。
  • 每个属性或者构造参数是一个确定的值或者容器中其他bean的引用。
  • 每个属性或者构成参数会被转换成属性或者构成参数的实际类型。

截止78/907页

2016年8月22日

自动注入

Mode Explanation
no (Default) No autowiring. Bean references must be defined via a ref element. Changing the default setting is not recommended for larger deployments, because specifying collaborators explicitly gives greater control and clarity. To some extent, it documents the structure of a system.
byName Autowiring by property name. Spring looks for a bean with the same name as the property that needs to be autowired. For example, if a bean definition is set to autowire by name, and it contains a master property (that is, it has a setMaster(..) method), Spring looks for a bean definition named master, and uses it to set the property.
byType Allows a property to be autowired if exactly one bean of the property type exists in the container. If more than one exists, a fatal exception is thrown, which indicates that you may not use byType autowiring for that bean. If there are no matching beans, nothing happens; the property is not set.
constructor Analogous to byType, but applies to constructor arguments. If there is not exactly one bean of the constructor argument type in the container, a fatal error is raised.

Bean的范围

Scope Description
singleton (Default) Scopes a single bean definition to asingle object instance per Spring IoC container.
prototype Scopes a single bean definition to any number ofobject instances.
request Scopes a single bean definition to the lifecycleof a single HTTP request; that is, each HTTPrequest has its own instance of a bean createdoff the back of a single bean definition. Onlyvalid in the context of a web-aware SpringApplicationContext.
session Scopes a single bean definition to the lifecycle ofan HTTP Session. Only valid in the context of aweb-aware Spring ApplicationContext.
globalSession Scopes a single bean definition to the lifecycleof a global HTTP Session. Typically onlyvalid when used in a Portlet context. Onlyvalid in the context of a web-aware SpringApplicationContext.
application Scopes a single bean definition to the lifecycle ofa ServletContext. Only valid in the context ofa web-aware Spring ApplicationContext.
websocket Scopes a single bean definition to the lifecycleof a WebSocket. Only valid in the context of aweb-aware Spring ApplicationContext.

截止96/907页