Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Spring DependsOn annotation cannot use to auto wire an interface

Tags:

java

spring

When I'm working on write some spring code, I'm using spring 4 with class and annotation-config. I have declared a bean implements an interface as a component. And I'm trying to make another bean to depends on it with its interface time. But it doesn't work because spring throws an error with no bean found in that name. I think it may because depends on is only work with concretive class auto wire, but I don't know why it set in this way? Is anyone could explain why depends on annotation don't allow type auto wire to an interface?

The simple sample code is like this

@Component
class A implement B{
}

@Component
@DependsOn("B")
class C {
}

the code above cannot work unless I change @DependsOn("B") to @DependsOn("A")

like image 717
Liyuan Avatar asked Oct 16 '25 19:10

Liyuan


1 Answers

In general DependsOn should never be used. If you ever need to it, you have probably done something wrong, or you have an extreme corner case. I have used Spring since 2006 and have not needed it yet.

The JavaDoc says

Used infrequently in cases where a bean does not explicitly depend on another through properties or constructor arguments, but rather depends on the side effects of another bean's initialization.

This basically means you only use DependsOn if you or some one else have written bad code. For instance one beans constructor creates a resource on disk that another bean needs when constructed. Springs IoC container and declarative wiring lets you control dependencies between beans, but in the extremely rare case where some legacy code has undeclared dependencies DependsOn lets you control the order unrelated spring beans are constructed.

like image 182
Klaus Groenbaek Avatar answered Oct 18 '25 09:10

Klaus Groenbaek