springboot之改变自动扫描的包

来源:互联网 发布:淘宝男士夏装 编辑:程序博客网 时间:2024/05/24 11:13

在开发中我们知道Spring Boot默认会扫描启动类同包以及子包下的注解,那么如何进行改变这种扫描包的方式呢,原理很简单就是:


@ComponentScan注解进行指定要扫描的包以及要扫描的类。

接下来我们简单写个例子进行测试下。


 第一步:新建两个新包

 我们在项目中新建两个包cn.kfit ; org.kfit ;


第二步:新建两个测试类;

在这里为了方便测试,我们让我们的类在启动的时候就进行执行,所以我们就编写两个类,实现接口CommandLineRunner,这样在启动的时候我们就可以看到打印信息了。

cn.kfit.MyCommandLineRunner1  :

1
2
3
4
5
6
7
8
9
10
11
12
package cn.kfit;
  
import org.springframework.boot.CommandLineRunner;
  
@Configuration
publicclass MyCommandLineRunner1 implements CommandLineRunner {
  
    @Override
    publicvoid run(String... args) throws Exception {
       System.out.println("MyCommandLineRunner1.run()");
    }
}

org.kfit.MyCommandLineRunner2  :

1
2
3
4
5
6
7
8
9
10
11
12
package org.kfit;
  
import org.springframework.boot.CommandLineRunner;
  
@Configuration
publicclass MyCommandLineRunner2 implements CommandLineRunner {
  
    @Override
    publicvoid run(String... args) throws Exception {
       System.out.println("MyCommandLineRunner2.run()");
    }
}

第三步:启动类进行注解指定

在App.java类中加入如下注解:

1
2
//可以使用:basePackageClasses={},basePackages={}
@ComponentScan(basePackages={"cn.kfit","org.kfit"})

启动如果看到打印信息:

1
2
3
MyCommandLineRunner1.run()
 
MyCommandLineRunner2.run()

说明我们配置成功了。

这时候你会发现,在App.java同包下的都没有被扫描了,所以如果也希望App.java包下的也同时被扫描的话,那么在进行指定包扫描的时候一定要进行指定配置:

1
@ComponentScan(basePackages={"cn.kfit","org.kfit","com.kfit"})
阅读全文
0 0
原创粉丝点击