返回

SpringBoot扫描注解使用与冲突原则

后端

SpringBoot扫描注解介绍

@SpringBootApplication

@SpringBootApplication 是 SpringBoot 中最重要的注解之一,它是一个组合注解,包含了以下三个注解:

  • @Configuration:表明该类是一个Spring配置类。
  • @EnableAutoConfiguration:启用 SpringBoot 的自动配置功能。
  • @ComponentScan:扫描指定包路径下的类,并将它们注册为 Spring Bean。

因此,如果我们在启动类上使用 @SpringBootApplication 注解,那么就相当于同时使用了 @Configuration、@EnableAutoConfiguration 和 @ComponentScan 这三个注解。

@ComponentScan

@ComponentScan 注解用于指定 SpringBoot 需要扫描的包路径。它可以单独使用,也可以与 @SpringBootApplication 注解一起使用。如果我们只使用 @ComponentScan 注解,那么就需要手动启用 SpringBoot 的自动配置功能,否则 SpringBoot 将不会自动扫描和注册 Spring Bean。

@ComponentScans

@ComponentScans 注解是 SpringBoot 2.x 中引入的新注解,它可以一次指定多个包路径进行扫描。它与 @ComponentScan 注解类似,但使用起来更加方便。

SpringBoot扫描注解冲突原则

当我们在启动类上同时使用 @SpringBootApplication、@ComponentScan 和 @ComponentScans 这三个注解时,可能会出现冲突。如果这三个注解指定了不同的扫描包路径,那么 SpringBoot 将会优先使用 @SpringBootApplication 注解指定的扫描包路径,然后是 @ComponentScans 注解指定的扫描包路径,最后是 @ComponentScan 注解指定的扫描包路径。

正确的注解选择和使用

通常情况下,我们只需要在启动类上使用 @SpringBootApplication 注解即可。如果我们确实需要指定额外的扫描包路径,那么可以使用 @ComponentScan 或 @ComponentScans 注解。但是,需要注意的是,这三个注解之间可能存在冲突,因此我们应该尽量避免同时使用它们。

如果我们必须同时使用这三个注解,那么应该注意以下几点:

  • @SpringBootApplication 注解应该放在最前面,然后是 @ComponentScans 注解,最后是 @ComponentScan 注解。
  • @ComponentScan 注解和 @ComponentScans 注解指定的扫描包路径应该不重复。

举例

以下是一个使用 SpringBoot 扫描注解的示例:

@SpringBootApplication
@ComponentScans(value = {
        @ComponentScan(basePackages = "com.example.demo1"),
        @ComponentScan(basePackages = "com.example.demo2")
})
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

在这个示例中,我们使用了 @SpringBootApplication 注解和 @ComponentScans 注解。@SpringBootApplication 注解扫描了 com.example.demo1 和 com.example.demo2 这两个包路径下的类。@ComponentScans 注解扫描了 com.example.demo3 和 com.example.demo4 这两个包路径下的类。

结论

SpringBoot 扫描注解是用于指定 SpringBoot 需要扫描的包路径。SpringBoot 中有三种扫描注解,分别是 @SpringBootApplication、@ComponentScan 和 @ComponentScans。@SpringBootApplication 注解是一个组合注解,包含了 @Configuration、@EnableAutoConfiguration 和 @ComponentScan 这三个注解。@ComponentScan 注解用于单独指定扫描包路径。@ComponentScans 注解是 SpringBoot 2.x 中引入的新注解,它可以一次指定多个包路径进行扫描。当这三个注解同时使用时,SpringBoot 将会优先使用 @SpringBootApplication 注解指定的扫描包路径,然后是 @ComponentScans 注解指定的扫描包路径,最后是 @ComponentScan 注解指定的扫描包路径。通常情况下,我们只需要在启动类上使用 @SpringBootApplication 注解即可。如果我们确实需要指定额外的扫描包路径,那么可以使用 @ComponentScan 或 @ComponentScans 注解。但是,需要注意的是,这三个注解之间可能存在冲突,因此我们应该尽量避免同时使用它们。