1.导包

实现基本功能只需要5个

spring初学(一)

test是为了测试、test包需要结合junit使用

2.编写测试类

spring初学(一)

CDPlayerConfig

package com.spring.pojo;

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

@Configuration
@ComponentScan
public class CDPlayerConfig {

}

CompactDisc接口

package com.spring.pojo;

interface CompactDisc {
	void play();
}

SgtPeppers子类

package com.spring.pojo;

import org.springframework.stereotype.Component;

@Component
public class SgtPeppers implements CompactDisc {
	private String title = "Sgt pepper is lonly heart";
	private String artist = "The Beatles";
	@Override
	public void play() {
		System.out.println("playing " + title + " by "+ artist);

	}

}

测试类:

package com.spring.pojo;

import static org.junit.Assert.assertNotNull;

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 Junit1 {
	
	@Autowired
	private CompactDisc compactDisc;
	
	@Test
	public void test1() {
		assertNotNull(compactDisc);
	}

}

测试结果:

spring初学(一)

报这个异常是因为spring本身没有日志,需要自己添加,我添加的是这两个 ,还要导入aop包

spring初学(一)

spring初学(一)

相关文章: