SPRING IN ACTION 第4版笔记-第二章-002-@ComponentScan、@Autowired的用法

一、@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 }

 

posted @ 2016-03-01 15:51  shamgod  阅读(908)  评论(0编辑  收藏  举报
haha