IT大道IT大道

首页 >  技术 > spring自动装配Bean - 放心飞吧

spring自动装配Bean - 放心飞吧

原文 http://blog.csdn.net/dream361/article/details/53714981 2016-12-17 22:31:33 0 评论

自动装配为注解方式,注解分为spring规范   和  java依赖注入规范:

java依赖注入规范在javax.inject.包中,需要下载jar包,我使用了maven,所以引入jar很简单:

itdadao

实例:

1.写个bean接口

package test.soundsystem;

public interface CompactDisc {
	void play();
}
2.实现接口

package test.soundsystem;

import javax.inject.Named;

@Named
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);
	}
}
3.自动装配类

package test.soundsystem;

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

import test.voice.Book;

@Configuration
@ComponentScan(basePackageClasses={Book.class,CompactDisc.class})
public class CDPlayerConfig {
}

4.测试类:

package test.soundsystem;

import javax.inject.Inject;

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;

import test.voice.Book;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=CDPlayerConfig.class)
public class CDPlayerTest {
	@Autowired
	private CompactDisc cd;
	
	@Inject
	private Book book;
	
	@Test
	public void cdShouldNotBeNull(){
		cd.play();
		book.read();
	}
}


测试结果:

itdadao

Tags:spring  

标签列表