Component-Scan和@Component之间的区别? [英] Difference between Component-Scan and @Component ?
问题描述
由于我对Spring非常陌生,我对这些注释感到有些困惑. 我试图在Google上找到它,并找到了很多答案,但是我仍然不清楚.我知道@Component是@ Repository,@ Service和@Controller的超级注释,但是我仍然不确定何时使用@Component和何时使用@ComponentScan可以帮助我清楚地了解这两者吗注释,两者之间有什么区别.
I'm bit confused about these annotations, since I am very new to Spring. I tried to get it on google and found many answers but still, I did not got the clarity. I got to know that @Component is Super annotation for @Repository, @Service and @Controller, but I'm still in doubt when to use @Component and when to Use @ComponentScan Could any one help me to get clear understanding of these both annotations, and what is difference in both.
推荐答案
使用注释@ComponentScan,您可以告诉Spring您的Spring管理的组件在哪里.这些由Spring管理的组件可以使用@ Repository,@ Service,@ Controller和ofcourse @Component进行注释.
Using the annotation @ComponentScan , you can tell Spring where do your Spring-managed components lie. These Spring-Managed components could be annotated with @Repository,@Service, @Controller and ofcourse @Component.
例如-假设您的Spring管理组件位于com.example.test1和com.example.test2两个包中.然后您的componentScan将是这样的
For example - Lets say your spring-managed components lie inside 2 packages com.example.test1 and com.example.test2. Then your componentScan would be something like this
@ComponentScan(basePackages="com.example.test1","com.example.test2")
OfCourse注释ComponentScan还有很多其他元素.
OfCourse the annotation ComponentScan has a lot of other elements.
您可以在此处详细了解它们- https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/ComponentScan.html .
You can read more about them here - https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/ComponentScan.html.
另一方面,@Component是任何Spring-Managed组件的通用注释.例如-如果您在com.example.test1包中创建一个名为Testing的类,并使用Spring @Component进行注释.
On the other hand, @Component is a generic annotation for any Spring-Managed component. For example - If you create a class called Testing inside the package com.example.test1 and annotate with Spring @Component.
@Component
Class Testing
{
public Testing()
{
}
public void doSomething()
{
System.out.println("do something");
}
}
按照上面的示例,在组件扫描期间,它将被拾取并添加到应用程序上下文中.
Following the above example, During Component Scan it will be picked up and added to the application context.
希望这可以使事情变得很清楚:)
Hope this makes things clear :)
这篇关于Component-Scan和@Component之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!