Example usage for org.springframework.beans.factory.config BeanExpressionResolver evaluate

List of usage examples for org.springframework.beans.factory.config BeanExpressionResolver evaluate

Introduction

In this page you can find the example usage for org.springframework.beans.factory.config BeanExpressionResolver evaluate.

Prototype

@Nullable
Object evaluate(@Nullable String value, BeanExpressionContext evalContext) throws BeansException;

Source Link

Document

Evaluate the given value as an expression, if applicable; return the value as-is otherwise.

Usage

From source file:lodsve.core.condition.OnExpressionCondition.java

@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {

    String expression = (String) metadata.getAnnotationAttributes(ConditionalOnExpression.class.getName())
            .get("value");
    String rawExpression = expression;
    if (!expression.startsWith("#{")) {
        // For convenience allow user to provide bare expression with no #{} wrapper
        expression = "#{" + expression + "}";
    }/*  w w w .  j a v a 2  s . c o m*/

    // Explicitly allow environment placeholders inside the expression
    expression = context.getEnvironment().resolvePlaceholders(expression);
    ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
    BeanExpressionResolver resolver = (beanFactory != null) ? beanFactory.getBeanExpressionResolver() : null;
    BeanExpressionContext expressionContext = (beanFactory != null)
            ? new BeanExpressionContext(beanFactory, null)
            : null;
    if (resolver == null) {
        resolver = new StandardBeanExpressionResolver();
    }
    boolean result = (Boolean) resolver.evaluate(expression, expressionContext);

    StringBuilder message = new StringBuilder("SpEL expression");
    if (metadata instanceof ClassMetadata) {
        message.append(" on " + ((ClassMetadata) metadata).getClassName());
    }
    message.append(": " + rawExpression);
    return new ConditionOutcome(result, message.toString());
}

From source file:org.springframework.beans.factory.DefaultListableBeanFactoryTests.java

@Test
public void testExpressionInStringArray() {
    DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
    BeanExpressionResolver beanExpressionResolver = mock(BeanExpressionResolver.class);
    when(beanExpressionResolver.evaluate(eq("#{foo}"), ArgumentMatchers.any(BeanExpressionContext.class)))
            .thenReturn("classpath:/org/springframework/beans/factory/xml/util.properties");
    bf.setBeanExpressionResolver(beanExpressionResolver);

    RootBeanDefinition rbd = new RootBeanDefinition(PropertiesFactoryBean.class);
    MutablePropertyValues pvs = new MutablePropertyValues();
    pvs.add("locations", new String[] { "#{foo}" });
    rbd.setPropertyValues(pvs);/* www .  j  a v  a 2 s.  c  o  m*/
    bf.registerBeanDefinition("myProperties", rbd);
    Properties properties = (Properties) bf.getBean("myProperties");
    assertEquals("bar", properties.getProperty("foo"));
}

From source file:org.springframework.boot.autoconfigure.condition.OnExpressionCondition.java

@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {

    String checking = ConditionLogUtils.getPrefix(logger, metadata);

    String value = (String) metadata.getAnnotationAttributes(ConditionalOnExpression.class.getName())
            .get("value");
    if (!value.startsWith("#{")) {
        // For convenience allow user to provide bare expression with no #{} wrapper
        value = "#{" + value + "}";
    }//from  w  w w  . j a va2 s .com
    if (logger.isDebugEnabled()) {
        StringBuilder builder = new StringBuilder(checking).append("Evaluating expression");
        if (metadata instanceof ClassMetadata) {
            builder.append(" on " + ((ClassMetadata) metadata).getClassName());
        }
        builder.append(": " + value);
        logger.debug(builder.toString());
    }
    // Explicitly allow environment placeholders inside the expression
    value = context.getEnvironment().resolvePlaceholders(value);
    ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
    BeanExpressionResolver resolver = beanFactory.getBeanExpressionResolver();
    BeanExpressionContext expressionContext = (beanFactory != null)
            ? new BeanExpressionContext(beanFactory, null)
            : null;
    if (resolver == null) {
        resolver = new StandardBeanExpressionResolver();
    }
    boolean result = (Boolean) resolver.evaluate(value, expressionContext);
    if (logger.isDebugEnabled()) {
        logger.debug(checking + "Finished matching and result is matches=" + result);
    }
    return result;
}

From source file:org.springframework.test.context.junit.jupiter.AbstractExpressionEvaluatingCondition.java

private <A extends Annotation> boolean evaluateExpression(String expression, boolean loadContext,
        Class<A> annotationType, ExtensionContext context) {

    Assert.state(context.getElement().isPresent(), "No AnnotatedElement");
    AnnotatedElement element = context.getElement().get();
    GenericApplicationContext gac = null;
    ApplicationContext applicationContext;

    if (loadContext) {
        applicationContext = SpringExtension.getApplicationContext(context);
    } else {/* www .  j a  va2  s. co m*/
        gac = new GenericApplicationContext();
        gac.refresh();
        applicationContext = gac;
    }

    if (!(applicationContext instanceof ConfigurableApplicationContext)) {
        if (logger.isWarnEnabled()) {
            String contextType = applicationContext.getClass().getName();
            logger.warn(String.format(
                    "@%s(\"%s\") could not be evaluated on [%s] since the test "
                            + "ApplicationContext [%s] is not a ConfigurableApplicationContext",
                    annotationType.getSimpleName(), expression, element, contextType));
        }
        return false;
    }

    ConfigurableBeanFactory configurableBeanFactory = ((ConfigurableApplicationContext) applicationContext)
            .getBeanFactory();
    BeanExpressionResolver expressionResolver = configurableBeanFactory.getBeanExpressionResolver();
    Assert.state(expressionResolver != null, "No BeanExpressionResolver");
    BeanExpressionContext beanExpressionContext = new BeanExpressionContext(configurableBeanFactory, null);

    Object result = expressionResolver.evaluate(configurableBeanFactory.resolveEmbeddedValue(expression),
            beanExpressionContext);

    if (gac != null) {
        gac.close();
    }

    if (result instanceof Boolean) {
        return (Boolean) result;
    } else if (result instanceof String) {
        String str = ((String) result).trim().toLowerCase();
        if ("true".equals(str)) {
            return true;
        }
        Assert.state("false".equals(str),
                () -> String.format("@%s(\"%s\") on %s must evaluate to \"true\" or \"false\", not \"%s\"",
                        annotationType.getSimpleName(), expression, element, result));
        return false;
    } else {
        String message = String.format("@%s(\"%s\") on %s must evaluate to a String or a Boolean, not %s",
                annotationType.getSimpleName(), expression, element,
                (result != null ? result.getClass().getName() : "null"));
        throw new IllegalStateException(message);
    }
}

From source file:org.springframework.test.context.junit.jupiter.DisabledIfCondition.java

private boolean isDisabled(String expression, ExtensionContext extensionContext) {
    ApplicationContext applicationContext = SpringExtension.getApplicationContext(extensionContext);

    if (!(applicationContext instanceof ConfigurableApplicationContext)) {
        if (logger.isWarnEnabled()) {
            String contextType = (applicationContext != null ? applicationContext.getClass().getName()
                    : "null");
            logger.warn(String.format(
                    "@DisabledIf(\"%s\") could not be evaluated on [%s] since the test "
                            + "ApplicationContext [%s] is not a ConfigurableApplicationContext",
                    expression, extensionContext.getElement(), contextType));
        }/*ww  w .j  a v a2 s .  com*/
        return false;
    }

    ConfigurableBeanFactory configurableBeanFactory = ((ConfigurableApplicationContext) applicationContext)
            .getBeanFactory();
    BeanExpressionResolver expressionResolver = configurableBeanFactory.getBeanExpressionResolver();
    BeanExpressionContext beanExpressionContext = new BeanExpressionContext(configurableBeanFactory, null);

    Object result = expressionResolver.evaluate(configurableBeanFactory.resolveEmbeddedValue(expression),
            beanExpressionContext);

    Assert.state((result instanceof Boolean || result instanceof String),
            () -> String.format("@DisabledIf(\"%s\") must evaluate to a String or a Boolean, not %s",
                    expression, (result != null ? result.getClass().getName() : "null")));

    boolean disabled = (result instanceof Boolean && ((Boolean) result).booleanValue())
            || (result instanceof String && Boolean.parseBoolean((String) result));

    return disabled;
}