实现自动装配需要用注解:注解分为 spring规范和java规范 ,java规范需要引入javax.inject 包 ,使用maven,直接引入。
从中可以看到 @Named @Inject属于java规范,@Component @Autowired @Resource属于spring注解
@Named大致等效于@Component 而@Inject和@Autowired也相似,但是@Inject要强制注入,@Autowired(required=false)可以选择略过不报异常
实例:
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();
}
}
测试结果: