spring 仅在一个类中使用 @ComponentScan 或 <context:component-scan />
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21022117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using @ComponentScan or <context:component-scan /> with only one class
提问by Shadi
I'm maintaining a project with two set of main packages, the project is using Spring and Spring MVC, one of these packages contains several controllers and is scanned using XML configuration (<context:component-scan />
).
我正在维护一个包含两组主要包的项目,该项目使用 Spring 和 Spring MVC,其中一个包包含多个控制器,并使用 XML 配置 ( <context:component-scan />
) 进行扫描。
The problem is that there is a single class in the other package (not scanned), and I need this class to be scanned, but only this class and nothing else in the package. I can't change its package now since it would be too risky now.
问题是在另一个包中只有一个类(未扫描),我需要扫描这个类,但只有这个类,包中没有其他内容。我现在不能改变它的包,因为它现在太冒险了。
So is there a way to do this using annotationsor XML ?
那么有没有办法使用注释或 XML来做到这一点?
采纳答案by Bart
Simply add is as a bean to your context e.g.
只需将 is 作为一个 bean 添加到您的上下文中,例如
<bean class="my.package.MyClass" />
回答by Emerson Farrugia
What @Bart said for XML.
@Bart 对 XML 所说的话。
If you need to pull in that one class using annotations, add the following to one of your @Configuration
classes
如果您需要使用注释引入该类,请将以下内容添加到您的@Configuration
类之一
@ComponentScan(
basePackageClasses = YourClass.class,
useDefaultFilters = false,
includeFilters = {
@ComponentScan.Filter(type = ASSIGNABLE_TYPE, value = YourClass.class)
})
回答by Robert Hunt
In addition to the method described by Emerson Farrugia there is a less verbose solution which has been supported since Spring Framework 4.2 as mentioned in the documentation here.
除了 Emerson Farrugia 描述的方法之外,还有一个不那么冗长的解决方案,从 Spring Framework 4.2 开始就得到了支持,如此处的文档中所述。
As of Spring Framework 4.2,
@Import
also supports references regular component classes, analogous to theAnnotationConfigApplicationContext.register
method. This is particularly useful if you want to avoid component scanning, by using a few configuration classes as entry points to explicitly define all your components.
从 Spring Framework 4.2 开始,
@Import
也支持引用常规组件类,类似于AnnotationConfigApplicationContext.register
方法。如果您想避免组件扫描,这将特别有用,通过使用一些配置类作为入口点来显式定义所有组件。
So your example would simply become:
所以你的例子会变成:
@Import(YourClass.class)
回答by Pratik Shelar
You need to use filters to filter out other classes and just include your class which you want to be scanned
您需要使用过滤器过滤掉其他类,只包含您要扫描的类
<context:component-scan base-package="com.abc" >
<context:include-filter type="regex"
expression="com.abc.customer.dao.*DAO.*" />
</context:component-scan>