Component-Scan 和 @Component 之间的区别? [英] Difference between Component-Scan and @Component ?

查看:58
本文介绍了Component-Scan 和 @Component 之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对这些注释有点困惑,因为我对 Spring 非常陌生.我试图在谷歌上找到它并找到了很多答案,但仍然没有弄清楚.我开始知道@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-Managed 组件可以使用 @Repository、@Service、@Controller 和当然的 @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 管理组件位于 2 个包 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")

当然注释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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆