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 }
  • 相关阅读:
    Unique Paths II
    Search Insert Position
    Remove Duplicates from Sorted Array
    Swap Nodes in Pairs
    Merge Two Sorted Lists
    下载youtube 视频工具
    CloudSTack4.2 查看所有虚拟机API测试
    实现业务系统中的用户权限管理--实现篇
    实现业务系统中的用户权限管理--设计篇
    CloudStack4.2 更新全局参数
  • 原文地址:https://www.cnblogs.com/shamgod/p/5231312.html
Copyright © 2011-2022 走看看