javaspringspring-bean

How to execute a runnable instead of bean creation in Spring configuration?


There is a usual configuration creating beans and performing an action using some of them.

The intention of initialAction is just execute print("Hello...") if certain conditions are in place (MyCondition.class). Obviously this return null is only required to keep the ceremony of beans creation and can be misleading for developers reading the code.

Is there a more elegant and convenient way to express the intention "run code after certain beans created if a condition is true"?

@Configuration
class App{

    @Bean
    @Conditional(MyCondition.class)
    Object initialAction() {
        var a = firstBean();
        var b = secondBean();

        print("Hello beans: $s, %s".formatted(a, b))

        return null;
    }

    MyEntity firstBean(){
      ...
    }

    MyEntity secondBean(){
      ...
    }

   // other beans
 }

Solution

  • There is an annotation @PostConstruct from javax or jakarta packages that are invoked once the dependency injection is done. Sadly, this cannot be combined with the @Conditional annotation.

    You can, however, create a dedicated @Configuration + @Conditional class using @PostConstruct:

    @Configuration
    @Conditional(MyCondition.class)
    public InitialActionConfiguration {
    
        @Autowired
        @Qualifier("firstBean")
        private MyEntity firstBean;
    
        @Autowired
        @Qualifier("secondBean")
        private MyEntity secondBean;
    
        @PostConstruct
        public void postConstruct() {
            print("Hello beans: %s, %s".formatted(firstBean, secondBean));
        }
    
        // initializations in other @Configuration class
    }
    

    Once you do this, both MyEntity beans got initialized (if properly defined as beans) and this configuration class autowires them and prints them out only if the condition defined by MyCondition is satisfied.