Spring3学习笔记(3)

本节主要记录下自动装配Bean。

步骤:1、创建可以被发现的bean。----创建一个小孩

           2、为组件扫描的bean命名。----给小孩报户口 

---------------------以上为创建bean-------下面是使用的时候-------------------------------

           3、用的时候:设置组件扫描,扫描基础包

           4、通过添加注解实现自动装配。

--------------------完成-----------------------------

           5、验证自动装配。

下面是针对上面的步骤实际代码:

第一步:创建一个唱片(CompactDisc)接口,其中只有一个操作就是Play();然后实例化这个唱片

package com.learn.spring;

public interface CompactDisc {
	void play();
}
package com.learn.spring;

import org.springframework.stereotype.Component;

@Component
public class SgtPeppers implements CompactDisc{

	private String title = "Heart band";
	private String artist = "The beatles";
	public void play() {
		System.out.println("Playing:" + title   + "by" + artist);
		
	}

}

注:上面实例化代码中的 @Component 表示该类会作为组件类。

第二步:也就是给上面的实体类报户口

package com.learn.spring;


import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan
public class CDPlayerConfig {

}

注:这里面比较重要的就是两个注解  @ComponentScan 默认会扫描与配置类相同的包,也就是前面标记 @Component的实体类。@Configuration 表明这个这个类是一个配置类,包含了Spring应用上下文如何创建bean的细节。

第3-5步:这里因为取-用-测试都在一体,故进行合并。

package com.learn.spring;


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)
@ContextConfiguration(classes=CDPlayerConfig.class)
public class CDPlayerTest {
	
	@Autowired
	private SgtPeppers sgtPeppers;
	
	@Test
	public void test(){
		sgtPeppers.play();
	}	
}

注2:在这里有几个比较重要的注解,逐一解释。

(1)@Autowired在前面声明bean,我们主要就是为了用。注册完成后,在这里使用的时候就需要进行自动装配。表明Spring创建CDPlayerbean的时候,会通过这个构造器实例化一个bean

(2)@ContextConfiguration(classes=CDPlayerConfig.class) Spring整合JUnit4测试时,使用注解引入多个配置文件

(3)@RunWith(SpringJUnit4ClassRunner.class),让测试运行于Spring测试环境

综上,执行,得到结果:

猜你喜欢

转载自blog.csdn.net/sinat_36220051/article/details/81158755