Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do Spring @Component classes have to be public?

Tags:

java

spring

I'd like to expose a component's interface as an interface and the implementing class would be package protected (and maybe in some other package):

package baz.iface

interface Foo {
    void bar();
}  


package baz.whatever

@Component
class SpringyFoo implements baz.iface.Foo {
    public void bar() { frobnicate(); }
}

Assuming baz.whatever is in the component-scan, will Spring be able to autowire a baz.iface.Foo somewhere else?

class FooClient {
    @Autowired
    private baz.iface.Foo;
}
like image 767
Christopher Taylor Avatar asked Aug 19 '13 12:08

Christopher Taylor


People also ask

Do Spring components have to be public?

No, components don't have to be public. The only requirement is that they have a no-arg constructor.

Is @component and @bean same?

No. It is used to explicitly declare a single bean, rather than letting Spring do it automatically. If any class is annotated with @Component it will be automatically detect by using classpath scan. We should use @bean, if you want specific implementation based on dynamic condition.

Is @component a class level annotation?

@Component is a class-level annotation. It is used to denote a class as a Component. We can use @Component across the application to mark the beans as Spring's managed components. A component is responsible for some operations.


1 Answers

No, components dont have to be public. The only requirement is that they have a no-arg constructor.

like image 162
Evgeniy Dorofeev Avatar answered Oct 21 '22 03:10

Evgeniy Dorofeev