简体   繁体   中英

Spring @DependsOn inheritance behavior

I have an abstract class A and a bunch of subclasses, which are Spring beans defined using @Service annotation ( A itself is not annotated). And I also have some separate bean of type B .

What I need to achieve is to make all these A -beans to be initialized after bean B .

For now I've used @DependsOn('b') with all of these beans - and it worked. But I don't want to copy-paste this annotation for all further A -beans I may create in the future. So I've tried to put @DependsOn('b') to the abstract A -class only, but it didn't work: probably this annotation is not inherited.

So is there any other elegant way to achieve this behaviour instead of putting this annotation to each of subclasses?

Try to create a custom annotation, and replace @Service annotation on A beans with it

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Service
@DependsOn('b')
public @interface ServiceDependingOnB { 
    String value() default "";
}

use @Lazy instead of @DependsOn('b') if solve your use case.

@Lazy will be initialized by container only when that bean will be accessed somewhere in code

@Bean
@Lazy(value = true)
public A a(){
    return new A();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM