zoukankan      html  css  js  c++  java
  • (26)改变自动扫描的包【从零开始学Spring Boot】

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

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

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

     

    第一步:新建两个新包

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

     

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

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

    cn.kfit.MyCommandLineRunner1  :

    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  :

    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类中加入如下注解:

    //可以使用:basePackageClasses={},basePackages={}

    @ComponentScan(basePackages={"cn.kfit","org.kfit"})

     

    启动如果看到打印信息:

    MyCommandLineRunner1.run()

    MyCommandLineRunner2.run()

    说明我们配置成功了。

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

    @ComponentScan(basePackages={"cn.kfit","org.kfit","com.kfit"})

     

     

    Spring Boot 系列博客】

    0)前言【从零开始学Spring Boot :

    http://412887952-qq-com.iteye.com/blog/2291496

    1spring boot起步之Hello World【从零开始学Spring Boot:

    http://412887952-qq-com.iteye.com/blog/2291500

    2Spring Boot返回json数据【从零开始学Spring Boot

    http://412887952-qq-com.iteye.com/blog/2291508

    16Spring Boot使用Druid(编程注入)【从零开始学Spring Boot

    http://412887952-qq-com.iteye.com/blogs/2292376

    17Spring Boot普通类调用bean【从零开始学Spring Boot】:

    http://412887952-qq-com.iteye.com/blog/2292388

     

    更多查看博客:http://412887952-qq-com.iteye.com/blog

     

  • 相关阅读:
    linux常用命令使用指南
    小赢理财招聘 测试开发、专项
    小赢理财招聘 测试开发、专项
    【模板】普通平衡树
    about乘法逆元
    luogu P2234 [HNOI2002]营业额统计
    线性筛中求莫比乌斯函数‘
    欧拉函数
    围棋
    丛林中的路
  • 原文地址:https://www.cnblogs.com/hehehaha/p/6147116.html
Copyright © 2011-2022 走看看