How does SpringBoot specify the scan range of packages during testing

  • 2021-12-11 07:34:48
  • OfStack

Directory in the test how to specify the scope of the package scan in the past … so write through the @ SpringBootApplication annotation configuration container package scan scope configuration scan package scope how to modify the location of the package scan? Method 1 Method 2

How to specify the scan range of packages during testing

The @ SpringBootTest annotation, in SpringBoot at startup scans the current class and the classes under its child packages according to @ SpringBootApplication on the main startup class. The container fails when the same class name appears in the child package.

This can be done by specifying a different ID for the same class, or by referring to the package scan range of the container during SpringBoot testing.

The details are as follows:

In the past … it was written like this


@RunWith(SpringRunner.class)
@SpringBootTest
public class IocTest {
 /**  Test method, etc ... */
}

Configure the package scanning scope of the container with the @ SpringBootApplication annotation


@RunWith(SpringRunner.class)
@SpringBootApplication(scanBasePackages = "com.example.xxx")
public class IocTest {
 /**  Test method, etc ... */
}

Configure scan package range

Recently, I studied the spring framework of java, and learned that the scope of package scanning needs to be configured when using annotations. However, I can't find a configuration similar to spring in the configuration file of SpringBoot project


<context:component-scan base-package= " XX.XX " /> 

After consulting the data, SpringBoot actually has a default package scanning mechanism, and the current package where the startup class is located and the subclasses of the package will be scanned by default. Therefore, when novices learn this framework, sometimes the annotation failure caused by the failure of scanning due to the fact that bean and the startup class are not in one folder.

Startup class: The entry function of the project. The generic naming convention is xxxApplication. java, and it is annotated with @ SpringBootApplication. There are also main functions in our common java.

How do I modify the location of packet scanning?

Method 1

Configure scanBasePackages in the SpringBootApplication annotation of the startup class, as follows


@SpringBootApplication(scanBasePackages = "org.sang.service")

You can also configure multiple package paths


@SpringBootApplication(scanBasePackages = {"org.sang.bean","org.sang.service"})

Method 2

Configure basePackages by adding @ ComponentScan annotation to the startup class


@ComponentScan(basePackages = {"org.sang.bean","org.sang.service"})

Choose 1 of the two configuration methods.


Related articles: