第一章
簡化Java開發(fā)
- 基于POJO的輕量級和最小侵入性編程
- 通過依賴注入和面向接口實(shí)現(xiàn)松耦合
- 基于切面和慣例進(jìn)行聲明式編程
- 通過切面和模板減少樣板式代碼
第二章
2.1Spring配置方案
- XML
- Java Config
- 自動化裝配
2.1.1自動化裝配
A. 組件掃描(component scan)
自動發(fā)現(xiàn)配置
| 配置方式 | 使用元素 |
|---|---|
| @Configuration | @ComponentScan(value="package", basePackages={"",""}) |
| XML | <context:component-scan> |
bean注解
| Spring | JSR330(Java Dependency Injection) | value屬性 |
|---|---|---|
| @Component | @Named | bean id |
B. 自動裝配(autowiring)
Spring|JSR330(Java Dependency Injection)
---|---|---
@Autowired|@Inject
2.1.2JavaConfig裝配
- 主要用于將第三方庫的組件裝配為bean
- 配置代碼,不應(yīng)包含業(yè)務(wù)邏輯
- 強(qiáng)大,類型安全,重構(gòu)友好
@Bean注解
方法名或者注解name屬性作為bean的id,Spring會攔截所有@Bean標(biāo)注的方法的調(diào)用,不會每次都進(jìn)行實(shí)際的調(diào)用,而會直接返回該方法創(chuàng)建的bean(所以多次調(diào)用返回的是同一個對象)
2.1.3XML裝配
<construct-arg> 構(gòu)造器配置
<property> setter配置
<util:list> util命名空間將某個類型的值或者引用暴露為bean
第三章
3.1 Profile
@Profile("dev") | <beans profile="dev">
通過spring.profiles.active和spring.profiles.default來配置,可以在如下的地方配置;
- DispatcherServlet的初始化參數(shù)<init-param>
- Web應(yīng)用的上下文參數(shù)<context-param>
- JNDI條目
- 環(huán)境變量
- JVM系統(tǒng)屬性
- 測試類上,@ActiveProfiles
3.2 條件bean
@Conditional(Condition.class)
public interface Condition {
/**
* Determine if the condition matches.
* @param context the condition context
* @param metadata metadata of the {@link org.springframework.core.type.AnnotationMetadata class}
* or {@link org.springframework.core.type.MethodMetadata method} being checked.
* @return {@code true} if the condition matches and the component can be registered
* or {@code false} to veto registration.
*/
boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata);
}
3.3消除自動裝配的歧義
@Autowired and @Inject
- Matches by Type
- Restricts by Qualifiers
- Matches by Name
@Resource
- Matches by Name
- Matches by Type
- Restricts by Qualifiers (ignored if match is found by name)
3.4bean作用域
@Scope(value=WebApplicationContext.SCOPE_SESSION, proxyMode=ScopedProxyMode.INTERFACES)
<bean scope="session">
<aop:scoped-proxy proxy-target-class="false" />
</bean>
3.5運(yùn)行時值注入
- property placeholder
- SpEL
3.5.1placeholder
- @PropertySource("properties") 配置文件源
- @Bean PropertySourcesPlaceholderConfigurer | <context:property-placeholder> 解析占位符${}
- 使用占位符->Environment
3.5.2SpEL
- 使用bean id引用bean
- 調(diào)用方法和訪問屬性
- 進(jìn)行邏輯、關(guān)系和算術(shù)運(yùn)算
- 正則表達(dá)式 matches 返回true|false
- 集合操作
[index]
.?[test expression] 用于生成滿足條件的子集
.^[test] | .$[test] 查詢第一個和最后一個匹配項(xiàng)
.![attribute] 投影元素的特定屬性,生成這個屬性的集合
"#{1}" 字面值
"#{beanid.method()|attribute}" 獲取bean的方法和屬性
"#{T(com.meizu.yard.spring.Env).getProperty('ebk.database.url')}" 讀取配置文件(類作用域的方法和屬性)
"#{systemProperties['jdk']}" 系統(tǒng)屬性