zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    属性注入(依赖注入)
    Spring之ioc
    Spring初始案例
    ::before和::after伪元素、:visited和:link、transform: scaleX(2);的使用
    给博客博文加上日期分类(set、map)
    Jquery父子选取心得
    先从css3开始拾起
    尝试博客文章一号
    Response.setContentType()
    pom配置详解
  • 原文地址:https://www.cnblogs.com/shamgod/p/5231312.html
Copyright © 2011-2022 走看看