春天@Component有什么用? [英] What's the use of @Component in spring?

查看:99
本文介绍了春天@Component有什么用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Guice没有类似的概念.例如,Guice可以使用默认构造函数自动注入任何类,而无需任何特殊的类注释.为什么Spring在启动时必须了解每个bean?出于自动装配的目的,spring不能只从类路径中查找类吗?我能想到的一个原因是AOP.但是,如果您不使用AOP,则整个bean定义计算都会增加大量的启动时间,这完全没有必要.

Guice does not have a similar concept. For example, Guice can automatically inject any class with a default constructor without the need for any special class annotation. Why does spring have to know about every bean on startup? For the purposes of autowiring, cant spring just lookup the class from the classpath? One reason I can think of is for AOP. But if you're not using AOP, the whole bean definition computation adds a significant amount of startup time which is totally unnecessary.

明确地说,我想让Spring根据需要从类路径中查找一个类

Explicitly, I want spring to lookup a class on demand from the classpath

@Component
class Bar {

}

@Component
class Foo {
    @Autowired Bar bar;
    public void doSomething() {}
}

因此,当我使用 getBean()创建bean Foo 时,spring会发现它需要一个 Bar ,因此它可以简单地查找 Bar .Guice就是这样做的,它避免了不必要的组件扫描,而这在开发过程中非常慢.

So When I create the bean Foo by using getBean() spring can see that it needs a Bar so it can simply lookup Bar on the classpath. This is what Guice does, and it avoids unnecessary component scanning which is terribly slow during development.

推荐答案

@Component @Repository @Controller @Service 注释定义了Spring IoC容器可以组件扫描"的各种bean.您可以在定义Spring上下文时指定扫描哪个程序包.

@Component, @Repository, @Controller, @Service annotations defines various beans that can be "component scanned" by Spring IoC container. You can specify which package is scanned when you are defining Spring context.

您可以显式使用类来创建注册Spring Bean.在这种情况下,您不需要使用注释.

You can use class explicitly to create register Spring bean. In such case you don't need to use annotations.

AFAIK没有使用注释不会自动扫描bean.我个人喜欢这样一个事实,即从类中看它是由IoC容器驱动的(当您使用组件扫描时),这一点很明显.希望这种没有注释的扫描想法永远不会渗透到Spring中.

AFAIK there isn't automatic scanning for beans without using annotations. I personally like the fact that it is obvious from looking at the class that it's driven by IoC container (when you are using component scanning). Hope this idea of scanning without annotations never penetrate into Spring.

编辑

是的,但是您需要将此类注册为Bean.Java Config的示例:

Yes it can, but you need to register this class as a bean. Example with Java Config:

@Configuration
public class SpringConfig{

    @Bean
    public Bar createBarBean(){
        new Bar();
    }
}

但是我相信这对您来说并不方便,因为您不想显式注册每个bean.那太过分了.

But I believe this wouldn't be handy for you, because you don't want to register each bean explicitly. That would be overkill.

以下是Spring文档的一些相关部分:

Here are some relevant parts of Spring docs:

我不知道其他任何bean查找机制.

I am not aware of any other bean lookup mechanism.

这篇关于春天@Component有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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