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

Pet*_*son 76 java spring annotations

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

实际开始是完成的

new AnnotationConfigApplicationContext(MyRootConfigurationClass.class);
Run Code Online (Sandbox Code Playgroud)

此Configuration类使用注释

@Configuration
@ComponentScan("com.my.package")
public class MyRootConfigurationClass
Run Code Online (Sandbox Code Playgroud)

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

@Configuration
@ComponentScan("com.my.package.first,com.my.package.second")
public class MyRootConfigurationClass
Run Code Online (Sandbox Code Playgroud)

但是,这会失败,并告诉我无法找到使用@Component注释指定的组件.

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

谢谢

hag*_*age 139

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

@ComponentScan({"com.my.package.first","com.my.package.second"})
Run Code Online (Sandbox Code Playgroud)

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


Pra*_*cer 43

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

@ComponentScan(basePackageClasses = {ExampleController.class, ExampleModel.class, ExmapleView.class})
Run Code Online (Sandbox Code Playgroud)

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

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

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

  • 对于要扫描的包,您只需在包中指定一个类.这被称为标记类.如果您需要在没有类的层次结构中扫描更高的包,则spring建议使用"spring marker"接口或该包中定义的最终类的技术仅用于包扫描. (3认同)

mpr*_*hat 17

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

而不是这个:

@ComponentScan("com.my.package.first,com.my.package.second")
Run Code Online (Sandbox Code Playgroud)

用这个:

@ComponentScan({"com.my.package.first","com.my.package.second"})
Run Code Online (Sandbox Code Playgroud)


sha*_*ing 9

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

@ComponentScan(basePackages={"com.firstpackage","com.secondpackage"})
Run Code Online (Sandbox Code Playgroud)

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

public @interface ComponentScan {
String[] basePackages() default {};
}
Run Code Online (Sandbox Code Playgroud)


小智 5

您使用 ComponentScan 来扫描多个包

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