1

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.

sha
  • 614
  • 6
  • 16

1 Answers1

1

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

luboskrnac
  • 23,973
  • 10
  • 81
  • 92
  • Thanks, This answers my question, but I want something more: Can spring simply lookup a class on the classpath on demand when it needs a class to autowire into another class? That would eliminate component-scan. I've edited my question to be more specific. – sha Oct 08 '14 at 03:46