Automatically wiring beans

  Spring attacks automatic wiring from two angles:

    Component scanning—Spring automatically discovers beans to be created in the application context

    Autowiring—Spring automatically satisfies bean dependencies.


  Working together, component scanning and autowiring are a powerful force and can help keep explicit configuration to a minimum.

  The CD provides a nice illustration of how DI works. CD players are of little value unless you insert (or inject) a CD into them. You could say that a CD player depends on a CD to do its job.

  To bring this illustration to life in Spring, let’s establish the concept of a CD in Java. The following listing shows CompactDisc, an interface that defines a CD.

package cn.dt.spring.wiringBeans.autoWired.soundsystem;

public interface CompactDisc {
void play();
}

You still need an implementation of CompactDisc, though. In fact, you could have several CompactDisc implementations. In this case, you’ll start with one: the SgtPeppers class, as shown in the next listing.

package cn.dt.spring.wiringBeans.autoWired.soundsystem;

import org.springframework.stereotype.Component;

/**
* \@Component. This simple annotation identifies this class as a component class
* and serves as a clue to Spring that a bean should be created for the class.
* @author anuo
*
*/
/*
* All beans in a Spring application context are given an ID. What may not have been
apparent from the previous example is that although you didn’t explicitly give the
SgtPeppers bean an ID, it was given one derived from its class name. Specifically, the
bean was given an ID of sgtPeppers by lowercasing the first letter of the class name.
If you’d rather give the bean a different ID, all you have to do is pass the desired ID
as a value to the @Component annotation. For example, if you wanted to identify the
bean as lonelyHeartsClub, then you’d annotate the SgtPeppers class with @Component
like this:
*/
//@Component
@Component("lonelyHeartsClub")
public class SgtPeppers implements CompactDisc {
private String title = "Sgt. Pepper's Lonely Hearts Club Band";
private String artist = "The Beatles";
public void play() {
System.out.println("Playing " + title + " by " + artist);
} }

  What you should take note of is that SgtPeppers is annotated with @Component. This simple annotation identifies this class as a component class and serves as a clue to Spring that a bean should be created for the class. There’s no need to explicitly configure a SgtPeppers bean; Spring will do it for you because this class is annotated with @Component.

  Component scanning isn’t turned on by default, however. You’ll still need to write an explicit configuration to tell Spring to seek out classes annotated with @Component and to create beans from them. The configuration class in the following listing shows the minimal configuration to make this possible.

  

package cn.dt.spring.wiringBeans.autoWired.soundsystem;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/**
* Component scanning isn’t turned on by default, however.
* You’ll still need to write an explicit configuration to tell Spring to seek out
* classes annotated with /@Component and to create beans from them.
* /@Configuration 可以去掉,/@ComponentScan不能
* @author anuo
*
*/
@Configuration
@ComponentScan
/*
* \@ComponentScan 参数:basePackages,basePackageClasses
*/
public class CDPlayerConfig { }

  But for now, observe that CDPlayerConfig doesn’t explicitly define any beans itself. Instead, it’s annotated with @ComponentScan to enable component scanning in Spring.

  With no further configuration, @ComponentScan will default to scanning the same package as the configuration class. Therefore, because CDPlayerConfig is in the soundsystem package, Spring will scan that package and any subpackages underneath it, looking for classes that are annotated with @Component. It should find the CompactDisc class and automatically create a bean for it in Spring.

  Believe it or not, with only two classes created, you already have something that you can try out. To test that component scanning works, let’s write a simple JUnit test that creates a Spring application context and asserts that the CompactDisc bean is, in fact, created. CDPlayerTest in the next listing does precisely that.

  

package cn.dt.spring.wiringBeans.autoWired.soundsystem;

import static org.junit.Assert.*;

import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.StandardOutputStreamLog;
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; /**
* CDPlayerTest takes advantage of Spring’s SpringJUnit4ClassRunner to have a
* Spring application context automatically created when the test starts. And
* the /@ContextConfiguration annotation tells it to load its configuration from
* the CDPlayerConfig class. Because that configuration class includes
* /@ComponentScan, the resulting application context should include the
* CompactDisc bean
*
* @author anuo
*
*/
@SuppressWarnings("deprecation")
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = CDPlayerConfig.class)
public class CDPlayerTest {
@Rule
public final StandardOutputStreamLog log = new StandardOutputStreamLog();
@Autowired
private CompactDisc cd; @Autowired
private MediaPlayer player; @Test
public void cdShouldNotBeNull() {
assertNotNull(cd);
} @Test
public void play() {
player.play();
assertEquals("Playing Sgt. Pepper's Lonely Hearts Club Band" + " by The Beatles\n", log.getLog());
}
}

  CDPlayerTest takes advantage of Spring’s SpringJUnit4ClassRunner to have a Spring application context automatically created when the test starts. And the @ContextConfiguration annotation tells it to load its configuration from the CDPlayerConfig class. Because that configuration class includes @ComponentScan, the resulting application context should include the CompactDisc bean.

  

package cn.dt.spring.wiringBeans.autoWired.soundsystem;

public interface MediaPlayer {

    void play();
}
package cn.dt.spring.wiringBeans.autoWired.soundsystem;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; @Component
public class CDPlayer implements MediaPlayer {
private CompactDisc cd; /*
* Its constructor is annotated with @Autowired, indicating that
* when Spring creates the CDPlayer bean,40 CHAPTER 2 Wiring beans
* it should instantiate it via that constructor and pass in a bean
* that is assignable to CompactDisc.
*/
/*
* If there are no matching beans, Spring will throw an exception as the application
* context is being created. To avoid that exception,
* you can set the required attribute on @Autowired to false:
* \@Autowired(required=false)
*/
@Autowired
public CDPlayer(CompactDisc cd) {
this.cd = cd;
} /*
* The @Autowired annotation’s use isn’t limited to constructors.
* It can also be used on a property’s setter method.
* For example, if CDPlayer had a setCompactDisc() method
*/
/* @Autowired
public void setCompactDisc(CompactDisc cd) {
this.cd = cd;
}*/ public void play() {
cd.play();
} }

@Component:在spring扫描的时候会扫描有@Component的类,如果@Component没带参数,则spring为将类型首字母小写后的名称那个作为bean的name.

@Configure:标明此class为配置类

@ComponentScan:扫描的范围,如果没有参数,默认是与次类同目录以及子目录下带有@Component/@Bean的类 参数:basePackages/basePackageClasses

@ContextConfiguration(classes = CDPlayerConfig.class) :标明从CDPlayerConfig加载配置

@RunWith(SpringJUnit4ClassRunner.class) :test开始时自动创建spring application context。

@Autowired:自动注入,可用于constructor 、setter以及field,可设置@Autowired(required=false)来保证在没有可注入的bean时启动不抛出异常,但是可能会在运行中抛出空指针异常。当有多个符合可注入的bean时,会抛出exception indicating ambiguity in selecting a bean for autowiring 。


wiring bean via XML

  

Spring In action chapter1_wiringBeans的更多相关文章

  1. 1、Spring In Action 4th笔记(1)

    Spring In Action 4th笔记(1) 2016-12-28 1.Spring是一个框架,致力于减轻JEE的开发,它有4个特点: 1.1 基于POJO(Plain Ordinary Jav ...

  2. spring in action 4th --- quick start

    读spring in action. 环境搭建 quick-start依赖注入 面向切面 1.环境搭建 jdk1.8 gradle 2.12 Intelij idea 2016.2.1 1.1创建一个 ...

  3. ssh整合随笔(注解方式,Spring 管理action)

    Web.xml<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi=" ...

  4. Spring in action记录

    最近一段时间重新学习了一遍SPRING,现在对这些笔记整理一下,一来算是对之前的学习有一个交代,二来当是重新学习一次,三来可以留下备份 这次学习中以SPRING IN ACTION 4这学习资料,整书 ...

  5. Spring in Action 4th 学习笔记 之 AOP

    前提:本文中的AOP仅限于Spring AOP. 先说说为什么需要AOP 最简单的一个例子就是日志记录,如果想记录一些方法的执行情况,最笨的办法就是修改每一个需要记录的方法.但这,真的很笨... 好的 ...

  6. 学习spring in action 第一天

    这段时间,开始学习java吧,因为C sharp 学习了java的大量语法格式,所以,留意下,就不会错了,java 有的c sharp也有,而且之前我也学习过java的桌面开发,但是一下子上来就要自己 ...

  7. spring in action学习笔记十五:配置DispatcherServlet和ContextLoaderListener的几种方式。

    在spring in action中论述了:DispatcherServlet和ContextLoaderListener的关系,简言之就是DispatcherServlet是用于加载web层的组件的 ...

  8. spring in action 学习笔记十四:用纯注解的方式实现spring mvc

    在讲用纯注解的方式实现springmvc之前先介绍一个类:AbstractAnnotationDispatcherServletInitializer.这个类的作用是:任何一个类继承AbstractA ...

  9. spring in action 学习十一:property placeholder Xml方式实现避免注入外部属性硬代码化

    这里用到了placeholder特有的一个语言或者将表达形式:${},spring in action 描述如下: In spring wiring ,placeholder values are p ...

随机推荐

  1. paramiko模块-2

    如何用paramiko模块模拟登入服务器,并记录操作日志,起到审计的作用? 各个client ---(连接跳转机)--->(跳转机)------>各自的目标服务器. 目前我们公司的跳转机, ...

  2. LINUX退出当前进程——比较return、exit()

    1.在Linux中任何让一个进程退出 进程退出表示进程即将结束.在Linux中进程退出分为了正常退出和异常退出两种. 1>正常退出 a. 在main()函数中执行return . b.调用exi ...

  3. 如何在HTML中加载Flash(2种实现方法)_HTML/Xhtml_网页制作

    点评:如何在HTML中加载Flash,为网页添加更多的色彩,普通的网页以无法满足用户的需求,接下来为大家介绍下2种在HTML中加载Flash的方法,感兴趣的各位可以适当参考下,希望对你有所帮助 第一种 ...

  4. json_decode返回null 和synax error原因及处理

    $checkLogin ='[{"gdsincode":"1103293","gdsname":"鲜美来带鱼段800g" ...

  5. selenium--环境搭建步骤

    1.安装Python 2.安装setuptools 3.安装pip(Python3.X自带pip) 4.安装selenium(步骤在另一个博客中已提及)

  6. Python——函数中的关键字参数

    关键字参数 可变参数允许你传入0个或任意个参数,这些可变参数在函数调用时自动组装为一个tuple.而关键字参数允许你传入0个或任意个含参数名的参数,这些关键字参数在函数内部自动组装为一个dict.请看 ...

  7. awk 统计出现次数--转

    知识点: 1)数组 数组是用来存储一系列值的变量,可通过索引来访问数组的值. Awk中数组称为关联数组,因为它的下标(索引)可以是数字也可以是字符串. 下标通常称为键,数组元素的键和值存储在Awk程序 ...

  8. sqlite的简介

    第一步: 第二步,建立桥接文件 随便创建一个类,语言选择oc,然后它会问你是否创建桥接模式,然后你选择是就可以了 那个类可以删除了 在那份桥接文件中加入一句话#import <sqlite3.h ...

  9. Appium移动自动化测试之Java篇

    1.环境准备:创建模拟器请参考:http://www.cnblogs.com/mrjade/p/5803131.html 2.新建一个java project,[File]-->[New]--& ...

  10. 自动生成查找组件的lua代码

    本篇主要解决的问题是使用lua脚本编写unity业务逻辑时,自动生成一些查找组件及绑定控件事件的lua代码! 现在很多unity项目都是用ulua作为热更新解决方案,因此需要用lua来写相关的逻辑,经 ...