Understanding @DependsOn

In Spring framework, beans are initialized in some particular order and their life cycle is maintained by Spring container. But we can still customized it with one of the Spring’s annotation @DependsOn.

Lets’s Code

Configuration: –

Below code snippets are from the earlier repo which was used for @Conditional blog.

Lets say, we have requirement of loading one bean only after another bean gets loaded first. i.e. Bean DependsOnBean depends on another bean CustomConditionBean. Below is code to be written to achieve statement.

    @Bean("CustomCondition")
    public CustomConditionBean getCustomConditionBean(){
        return new CustomConditionBean();
    }

    @Bean
    @DependsOn("CustomCondition")
    public DependsOnBean getDependsOnBean(){
        return new DependsOnBean();
    }

Notes: –

  • In case of circular dependency @DependsOn will throw BeanCreationException and highlights that the beans have a circular dependency (Circular Dependency means, B1-> B2 -> B3 -> B1).
  • 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.
  • Using @DependsOn at the class level has no effect unless component-scanning is being used.
  • If a DependsOn-annotated class is declared via XML, DependsOn annotation metadata is ignored, and <bean depends-on="..."/> is respected instead.

The above code repo can be found here

Advertisements