sha
sha

Reputation: 643

What's the use of @Component in spring?

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.

EDIT:

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() {}
}

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.

Upvotes: 1

Views: 1398

Answers (1)

luboskrnac
luboskrnac

Reputation: 24561

@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.

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

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.

EDIT

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();
    }
}

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

Here are some relevant parts of Spring docs:

I am not aware of any other bean lookup mechanism.

Upvotes: 1

Related Questions