1

I'm providing a value via a conditional Bean. If the Condition is met everything is fine but if the condition is not met (hence the bean is not present) my code fails. is there some way to check if the bean is defined before hand. in SpEL ?

I tried something like #{someBean? someBean.myValue:null} but it does not work.

Gary Russell
  • 166,535
  • 14
  • 146
  • 179

1 Answers1

1

See this answer for why this works...

@SpringBootApplication
public class So56189689Application {

    public static void main(String[] args) {
        SpringApplication.run(So56189689Application.class, args);
    }

    @Value("#{containsObject('foo') ? getObject('foo').foo : null}")
    String foo;

    @Bean
    public ApplicationRunner runner() {
        return args -> System.out.println(foo);
    }

//  @Bean
//  public Foo foo() {
//      return new Foo();
//  }

    public static class Foo {

        private String foo = "bar";

        public String getFoo() {
            return this.foo;
        }

        public void setFoo(String foo) {
            this.foo = foo;
        }

    }

}

EDIT

The #root object of the SpEL Expression is a BeanExpressionContext, you can invoke containsObject() and getObject() methods on that context.

Here's the code from the BeanExpressionContext:

public boolean containsObject(String key) {
    return (this.beanFactory.containsBean(key) ||
            (this.scope != null && this.scope.resolveContextualObject(key) != null));
}


public Object getObject(String key) {
    if (this.beanFactory.containsBean(key)) {
        return this.beanFactory.getBean(key);
    }
    else if (this.scope != null){
        return this.scope.resolveContextualObject(key);
    }
    else {
        return null;
    }
}
Gary Russell
  • 166,535
  • 14
  • 146
  • 179