1. 装配(wiring)

创建应用对象之间协作关系的行为称为装配(wiring), 这也是依赖注入(DI)的本质.

2. spring装配机制:

1). 在XML中进行显式配置。

2). 在Java中进行显式配置。

public interface CompactDisc {void play();
}import org.springframework.stereotype.Component;/**   @Component注解。 这个简单的注解表明该类会作为组件类, * 并告知Spring要为这个类创建bean。 */
public class SgtPeppers implements CompactDisc{@Overridepublic void play() {System.out.println("config the beatles sing sgt. Pepper lonely hearts club band2");}
}public class CDPlayer{private CompactDisc cd;public CDPlayer(CompactDisc cd){this.cd = cd;}public void play() {cd.play();}
}import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;/** @Configuration注解表明这个类是一个配置类,
该类应该包含在Spring应用上下文中如何创建bean的细节。*/
@Configuration
public class CDPlayerConfig {/*@Bean注解会告诉Spring这个方法将会返回一个对象,该对象要注册为Spring应用上下文中的bean。方法体中包含了最终产生bean实例的逻辑。*/@Beanpublic CompactDisc sgtPeppers(){return new SgtPeppers();}@Beanpublic CDPlayer cdPlayer(CompactDisc cd){return new CDPlayer(cd);}
}import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;@RunWith(SpringJUnit4ClassRunner.class)  // 自动创建Spring的应用上下文
/* @ContextConfiguration会告诉它需要在CDPlayerConfig中加载配置。
因为CDPlayerConfig类中包含了@ComponentScan
*/
@ContextConfiguration(classes=CDPlayerConfig.class)
public class MyTest {@Autowiredprivate CompactDisc cd;@Autowiredprivate CDPlayer player;@Testpublic void test01(){cd.play(); player.play();}
}

3). 隐式的bean发现机制和自动装配。

spring从两个角度来实现自动化装配:  1). 组建扫描(component scanning): spring会自动发现应用上下文中所创建的bean。

2). 自动装配(autowiring):spring自动满足bean之间的依赖。

public interface CompactDisc {void play();
}import org.springframework.stereotype.Component;/**   @Component注解。 这个简单的注解表明该类会作为组件类, * 并告知Spring要为这个类创建bean。 */
@Component
public class SgtPeppers implements CompactDisc{@Overridepublic void play() {System.out.println("the beatles sing sgt. Pepper lonely hearts club band");}
}import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;/** 组件扫描默认是不启用的* @ComponentScan注解启用了组件扫描 * @ComponentScan默认会扫描与配置类相同的包。Spring将会扫描这个包以及这个包下的所有子包, 查找带
有@Component注解的类。*/
@Configuration
@ComponentScan
public class CDPlayerConfig {}import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;@RunWith(SpringJUnit4ClassRunner.class)  // 自动创建Spring的应用上下文
/* @ContextConfiguration会告诉它需要在CDPlayerConfig中加载配置。
因为CDPlayerConfig类中包含了@ComponentScan
*/
@ContextConfiguration(classes=CDPlayerConfig.class)
public class MyTest {@AutowiredCompactDisc cd;@Testpublic void test01(){cd.play();      }
}

当然如果你喜欢使用xml启动组件扫描,那么如下xml配置可以代替@ComponentScan

3. 在JavaConfig中引用xml配置

public interface CompactDisc {void play();
}import java.util.List;public class BlankDisc implements CompactDisc{private String title;private String artist;private List<String> tracks;public BlankDisc(String title, String artist, List<String> tracks) {super();this.title = title;this.artist = artist;this.tracks = tracks;}@Overridepublic void play() {System.out.println("xml,javaconfig混合使用");System.out.println("Playing "+title+" by"+artist);for(String track : tracks){System.out.println("-Track: "+track);}}
}public class CDPlayer{private CompactDisc cd;public CDPlayer(CompactDisc cd){this.cd = cd;}public void play() {cd.play();}
}import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;/** @Configuration注解表明这个类是一个配置类,
该类应该包含在Spring应用上下文中如何创建bean的细节。*/
@Configuration
public class CDPlayerConfig {/*@Bean注解会告诉Spring这个方法将会返回一个对象,该对象要注册为Spring应用上下文中的bean。方法体中包含了最终产生bean实例的逻辑。*/@Beanpublic CDPlayer cdPlayer(CompactDisc cd){return new CDPlayer(cd);}
}import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportResource;@Configuration
@Import(CDPlayerConfig.class)
@ImportResource("classpath:applicationContext.xml")
public class SoundSystemConfig {}import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;@RunWith(SpringJUnit4ClassRunner.class)  // 自动创建Spring的应用上下文
/* @ContextConfiguration会告诉它需要在CDPlayerConfig中加载配置。
因为CDPlayerConfig类中包含了@ComponentScan
*/
@ContextConfiguration(classes=SoundSystemConfig.class)
public class MyTest {//@Autowired//private CompactDisc cd;@Autowiredprivate CDPlayer player;@Testpublic void test01(){player.play();}
}

xml配置文件如下:

<?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 definitions here --><bean id="blankDisc" class="com.ag.test5.BlankDisc"><constructor-arg value="sgt. Pepper"/><constructor-arg><value>the beatles</value></constructor-arg><constructor-arg><list><value>getting better</value><value>fixing a hole</value></list></constructor-arg></bean>
</beans>

4. 条件化的bean

Spring 4引入了一个新的@Conditional注解, 它可以用到带有@Bean注解的方法上。 如果给定的条件计算结果为true, 就会创建这个bean, 否则的话, 这个bean会被忽略。

5. 处理自动装配的歧义性

发生歧义性的时候, Spring提供了多种可选方案来解决这样的问题。 你可以将可选bean中的某一个设为首选(primary) 的
bean(使用@Primary注解), 或者使用限定符(qualifier) 来帮助Spring将可选的bean的范围缩小到只有一个bean。

Cake,Cookies都实现了Dessert接口,但是注入到Dessert类型时, 会将Cookies注入进去,避免了"org.springframework.beans.factory.NoUniqueBeanDefinitionException"

6. bean的作用域

7. 运行时值注入

如果希望避免硬编码值, 而是想让这些值在运行时再确定。如下,我们不希望把字符串写死。

为了实现这些功能, Spring提供了两种在运行时求值的方式:

1)。 属性占位符(Property placeholder) 。

占位符的形式为使用"${}"包装的属性名称。

为了使用占位符, 我们必须要配置一个PropertyPlaceholderConfigurer bean或PropertySourcesPlaceholderConfigurer bean。 从Spring3.1开始, 推荐使用PropertySourcesPlaceholderConfigurer, 因为它能够基于Spring Environment及其属性源来解析占位符。

2)。Spring表达式语言(SpEL  Spring Expression Language)

SpEL拥有很多特性, 包括:
             ①使用bean的ID来引用bean;
             ②调用方法和访问对象的属性;
             ③对值进行算术、 关系和逻辑运算;
             ④正则表达式匹配;
             ⑤集合操作。

SpEL表达式要放到“#{ ... }”之中

SpEL可以表示字面值: 浮点数(#{3.14159}), String(#{'hello'})值以及Boolean(#{true})值。

SpEL还可以引用bean(#{sgtPeppers})、 属性(#{sgtPeppers.artist})和方法(#{artistSelector
.selectArtist()})

SpEL还可以使用T()在表达式中使用类型。

用来操作表达式值的SpEL运算符

运算符类型 运 算 符
算术运算 +、 -、 * 、 /、 %、 ^
比较运算 < 、 > 、 == 、 <= 、 >= 、 lt 、 gt 、 eq 、 le 、 ge
逻辑运算 and 、 or 、 not 、 │
条件运算 ?: (ternary) 、 ?: (Elvis)
正则表达式 matches

例如: #{2 * T(java.lang.Math).PI  *  circle.redius}    // 使用了乘法运算符(*)
     尽量让表达式简洁

spring:《spring实战》读后感二相关推荐

  1. Spring Boot 揭秘与实战(二) 数据缓存篇 - EhCache

    文章目录 1. EhCache 集成 2. 源代码 本文,讲解 Spring Boot 如何集成 EhCache,实现缓存. 在阅读「Spring Boot 揭秘与实战(二) 数据缓存篇 - 快速入门 ...

  2. Spring Boot 揭秘与实战(二) 数据缓存篇 - Guava Cache

    本文,讲解 Spring Boot 如何集成 Guava Cache,实现缓存. 博客地址:blog.720ui.com/ 在阅读「Spring Boot 揭秘与实战(二) 数据缓存篇 - 快速入门」 ...

  3. Vue + Spring Boot 项目实战(二十一):缓存的应用

    重要链接: 「系列文章目录」 「项目源码(GitHub)」 本篇目录 前言 一.缓存:工程思想的产物 二.Web 中的缓存 1.缓存的工作模式 2.缓存的常见问题 三.缓存应用实战 1.Redis 与 ...

  4. Spring Cloud实战小贴士:Zuul统一异常处理(二)

    在前几天发布的<Spring Cloud实战小贴士:Zuul统一异常处理(一)>一文中,我们详细说明了当Zuul的过滤器中抛出异常时会发生客户端没有返回任何内容的问题以及针对这个问题的两种 ...

  5. Spring Security 实战干货:OAuth2授权回调的核心认证流程

    1. 前言 我们在上一篇 Spring Security 实战干货:OAuth2 授权回调的处理机制 对 OAuth2 服务端调用客户端回调的流程进行了图解, 今天我们来深入了解 OAuth2 在回调 ...

  6. Spring Security 实战干货: RBAC权限控制概念的理解

    点击上方蓝色"程序猿DD",选择"设为星标" 回复"资源"获取独家整理的学习资料! 作者 | 码农小胖哥 来源 | 公众号「码农小胖哥」 1 ...

  7. Spring AOP 实战运用

    Spring AOP 实战 看了上面这么多的理论知识, 不知道大家有没有觉得枯燥哈. 不过不要急, 俗话说理论是实践的基础, 对 Spring AOP 有了基本的理论认识后, 我们来看一下下面几个具体 ...

  8. 我的新书《Spring Cloud实战》预告

    从去年6月开始编写<Spring Cloud构建微服务架构>系列博文开始,受到了不少同行的关注与支持.随后也开通了多个交流群.创建了相关的论坛(http://bbs.springcloud ...

  9. Spring Cloud实战小贴士:Zuul处理Cookie和重定向

    由于我们在之前所有的入门教程中,对于HTTP请求都采用了简单的接口实现.而实际使用过程中,我们的HTTP请求要复杂的多,比如当我们将Spring Cloud Zuul作为API网关接入网站类应用时,往 ...

  10. Spring Cloud实战小贴士:Zuul统一异常处理(一)

    在上一篇<Spring Cloud源码分析(四)Zuul:核心过滤器>一文中,我们详细介绍了Spring Cloud Zuul中自己实现的一些核心过滤器,以及这些过滤器在请求生命周期中的不 ...

最新文章

  1. JavaScript中 for、for in、for of、forEach等使用总结
  2. DB_Links创建际删除
  3. windows下安装composer方法(不修改PATH环境变量)
  4. 33、JAVA_WEB开发基础之会话机制
  5. 好的微服务架构=企业服务总线(ESB)的灭亡?
  6. cisco 9月24日 CCNA实验
  7. 图片放大不失真软件 S-Spline V2
  8. RAID5阵列掉盘显示未初始化---解决过程
  9. Box2dの学习制作超级积木完整版
  10. linux开发板命令rx,linux 常用命令汇总
  11. 如何在南方CASS中内插高程点
  12. 转置矩阵,矩阵的行列式,伴随矩阵,逆矩阵的概念及C#求解
  13. 清北学堂模拟赛d4t4 a
  14. 计算机二级word 文档排版,word排版操作指导(计算机二级2010版)
  15. word2vec:基于层级 softmax 和负采样的 Skip-Gram
  16. numpy中np.nan(pandas中NAN)
  17. 名词解释:失压、全失压、断相、失流、掉电(DL645-2007)
  18. TEA XTEA XXTEA
  19. 百度云网速慢?普通VIP也限速?用户激励措施太套路?Pandownload被举报?这些统统没关系,我们自己搭建一个私人云盘服务器
  20. 如何将RT-Thread移植到织女星开发板?

热门文章

  1. JavaWeb手机短信实现前台利用JS获取随机验证码,倒计时效果
  2. 《零基础入门学习Python》学习过程笔记【013元组】
  3. 祝各位节日快乐!20151111
  4. 实现集合类的元素删除和修改的一点实践。。。
  5. Python写爬虫只需三步
  6. 用MathType编辑带点星号的流程
  7. Telent 远程登录服务
  8. 抽屉效果的实现(DrawerLayout和SlidingMenu的对比)
  9. 使用Xib解决1px线条绘制的一些方法
  10. 中国WEB 2.0的质变过程