Search code examples
javaspringspring-annotations

@Conditionalonexpression on a class object getter


I was wondering if there is a way to enable a class using @conditionalonexpression during runtime by evaluating an object of a class which gets its value at runtime.

FOr example:

@ConditionalOnExpression(#{propertyobject.getexenabled()})
class ex1{

}

propertyobject instance is filled with value at runtime(Say at the beginning of the program) Is this possible to be achieved?


Solution

  • Yes, it is possible but getexenabled() method should be static.

    Like:

    @SpringBootApplication
    public class So44456388Application {
    
        public static void main(String[] args) {
            SpringApplication.run(So44456388Application.class, args);
        }
    
        public static class Evaluator {
            public static boolean getexenabled() {
                //your logic here
                return true /*false*/;
            }
        }
    
        @Component
        @ConditionalOnExpression("#{T(com.stackoverflow.so44456388.So44456388Application$Evaluator).getexenabled()}")
        public static class RichBean {
            @PostConstruct
            private void init() {
                System.out.println("RichBean");
            }
        }
    }