标签:
一、@ComponentScan
1.
@Configuration //说明此类是配置文件 @ComponentScan //开启扫描,会扫描当前类的包及其子包 public class CDPlayerConfig { }
2.
@ComponentScan(basePackages={"soundsystem", "video"})//扫描多个包 public class CDPlayerConfig { }
3.
@ComponentScan(basePackageClasses={CDPlayer.class,AAA.class})//指定要扫描的类 public class CDPlayerConfig { }
二、@Autowired
1.可以在构造方法中用
@Component public class CDPlayer implements MediaPlayer { private CompactDisc cd; @Autowired //@Inject public CDPlayer(CompactDisc cd) { this.cd = cd; } public void play() { cd.play(); } }
2.在set方法中
@Autowired public void setCompactDisc(CompactDisc cd) { this.cd = cd; }
3.在一般的方法中
@Autowired public void insertDisc(CompactDisc cd) { this.cd = cd; }
4.如果依赖不是必需的,可设置属性
@Autowired(required=false) public CDPlayer(CompactDisc cd) { this.cd = cd; }
5.可用@Inject替代
1 package soundsystem; 2 import javax.inject.Inject; 3 import javax.inject.Named; 4 @Named 5 public class CDPlayer { 6 ... 7 @Inject 8 public CDPlayer(CompactDisc cd) { 9 this.cd = cd; 10 } 11 ... 12 }
SPRING IN ACTION 第4版笔记-第二章-002-@ComponentScan、@Autowired的用法
标签:
原文地址:http://www.cnblogs.com/shamgod/p/5231312.html