如何使用@ComponentScan注释扫描多个路径?

问题描述 投票:74回答:7

我正在使用Spring 3.1并使用@Configuration@ComponentScan属性引导应用程序。

实际开始是完成的

new AnnotationConfigApplicationContext(MyRootConfigurationClass.class);

此Configuration类使用注释

@Configuration
@ComponentScan("com.my.package")
public class MyRootConfigurationClass

这很好用。但是我想更具体地说明我扫描的软件包,所以我试过了。

@Configuration
@ComponentScan("com.my.package.first,com.my.package.second")
public class MyRootConfigurationClass

然而,这失败了,并告诉我它无法找到使用@Component注释指定的组件。

做我正在做的事情的正确方法是什么?

谢谢

java spring annotations
7个回答
136
投票

@ComponentScan使用字符串数组,如下所示:

@ComponentScan({"com.my.package.first","com.my.package.second"})

当您仅在一个字符串中提供多个包名称时,Spring会将其解释为一个包名称,因此无法找到它。


42
投票

还有另一种类型安全的替代方法,可以将基本包位置指定为String。 See the API here,但我也在下面说明:

@ComponentScan(basePackageClasses = {ExampleController.class, ExampleModel.class, ExmapleView.class})

将basePackageClasses说明符与类引用一起使用将告诉Spring扫描这些包(就像上面提到的替代方法一样),但是这种方法既是类型安全的,又为将来的重构添加了IDE支持 - 这在我的书中是一个巨大的优势。

从API中读取,Spring建议在您希望扫描的每个包中创建一个无操作标记类或接口,除了用作/通过此属性的引用之外,其他目的不起作用。

IMO,我不喜欢标记类(但同样,它们就像package-info类一样)但是类型安全,IDE支持,并且大大减少了包含在此扫描中所需的基本包的数量毫无疑问,这是一个更好的选择。


17
投票

单独提供您的包名称,它需要String[]作为包名称。

而不是这个:

@ComponentScan("com.my.package.first,com.my.package.second")

用这个:

@ComponentScan({"com.my.package.first","com.my.package.second"})

9
投票

另一种方法是使用basePackages字段;这是ComponentScan注释中的一个字段。

@ComponentScan(basePackages={"com.firstpackage","com.secondpackage"})

如果从jar文件中查看ComponentScan注释.class,您将看到一个basePackages字段,它接受一个字符串数组

public @interface ComponentScan {
String[] basePackages() default {};
}

3
投票

您可以使用ComponentScan扫描多个包

@ComponentScan({"com.my.package.first","com.my.package.second"})


1
投票

确保在pom.xml中添加了此依赖项

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

0
投票

您还可以使用@ComponentScans注释:

@ComponentScans(value = { @ComponentScan("com.my.package.first"),
                          @ComponentScan("com.my.package.second") })
© www.soinside.com 2019 - 2024. All rights reserved.