您的位置 首页 java

Spring启用组件扫描之Java版本1

I唱片接口代码

 package 音响系统;

public interface I唱片 {
  void 播放();
}

  
 package 音响系统;

import org. Spring framework.stereotype.Component;

/**
 *
 * 没有必要显式配置`天之大专辑` Bean,
 * 因为这个类使用了`@Component`注解,
 * `@Component`表明该类会作为组件类,
 * 所以Spring会为你把事情处理妥当。
 *
 * 不过,**组件扫描默认是不启用的**。
 */@Component
public class 天之大专辑 implements I唱片 {

  private String 歌手 = " 费玉清 ";
  private String 专辑名 = "天之大";

  public void 播放() {
    System.out.println("播放专辑《" + 专辑名 + "》 by " + 歌手);
  }
}

  

天之大专辑 的具体内容并不重要。你要注意的是它使用了 @Component

@Component表明该类会作为组件类,并告知Spring要为这个类创建Bean。没有必要显式配置天之大专辑 Bean,因为这个类使用了@Component注解,所以Spring会为你把事情处理妥当。(需要启用组件扫描,在后文【启用组件扫描】有介绍)

I媒体播放器接口代码

 package 音响系统;

public interface I媒体播放器 {
  void 播放();
}

  
 package 音响系统;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class 唱片播放器 implements I媒体播放器 {
  private I唱片 唱片;

  @Autowired
  public 唱片播放器(I唱片 cd) {
    this.唱片 = cd;
  }

  public void 播放() {
    唱片.播放();
  }

}

  

如果你不将I唱片插入(注入)到I媒体播放器中,那么I媒体播放器其实是没有太大用处的。So,可以这样说,I媒体播放器依赖于I唱片才能完成它的使命。

启用组件扫描

组件扫描默认是不启用的 。我们还需要显式配置一下Spring,从而命令Spring去寻找带有@Component注解的类,并为其创建Bean。

 package 音响系统;

import org.springframework.context. Annotation .ComponentScan;
import org.springframework.context.annotation.Configuration;

/**
 * @ComponentScan 启用了组件扫描
 * 从而命令Spring去寻找带有`@Component`注解的类,并为其创建Bean。
 *
 * 【位置】@ComponentScan`默认会扫描与配置类相同的包,
 * 查找带有`@Component`的类。
 * 这样的话,就能发现`天之大专辑`,并且会在Spring中自动为其创建一个Bean。
 */@ Configuration 
@ComponentScan
public class 唱片播放器Config {
}
  

@ComponentScan,这个注解能够在Spring中启用组件扫描。

@ComponentScan默认会扫描与配置类相同的包,查找带有@Component的类。这样的话,就能发现天之大专辑,并且会在Spring中自动为其创建一个Bean。

看看效果

 package 音响系统;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class 播放Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(唱片播放器Config.class);

        I媒体播放器 播放器 = context.getBean(I媒体播放器.class);
        播放器.播放();
        context.close();
    }
}

  
 AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(唱片播放器Config.class);
  

输出:

 八月 07, 2021 10:12:23 上午 org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@7106e68e: startup date [Sat Aug 07 10:12:23 CST 2021]; root of context hierarchy
播放专辑《天之大》 by 费玉清
八月 07, 2021 10:12:23 上午 org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
信息: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@7106e68e: startup date [Sat Aug 07 10:12:23 CST 2021]; root of context hierarchy
  

所有的代码见:

 启用组件扫描之Java版本1
  

后面再写个用xml的例子。

文章来源:智云一二三科技

文章标题:Spring启用组件扫描之Java版本1

文章地址:https://www.zhihuclub.com/192461.shtml

关于作者: 智云科技

热门文章

网站地图