Bean 引用

如果评估上下文已使用 Bean 解析器配置,则可以通过使用@符号作为前缀从表达式中查找 Bean。以下示例显示了如何执行此操作

  • Java

  • Kotlin

ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
context.setBeanResolver(new MyBeanResolver());

// This will end up calling resolve(context, "someBean") on MyBeanResolver
// during evaluation.
Object bean = parser.parseExpression("@someBean").getValue(context);
val parser = SpelExpressionParser()
val context = StandardEvaluationContext()
context.setBeanResolver(MyBeanResolver())

// This will end up calling resolve(context, "someBean") on MyBeanResolver
// during evaluation.
val bean = parser.parseExpression("@someBean").getValue(context)

如果 Bean 名称包含点 (.) 或其他特殊字符,则必须以字符串文字形式提供 Bean 的名称,例如@'order.service'

要访问工厂 Bean 本身,您应该改为在 Bean 名称前添加&符号。以下示例显示了如何执行此操作

  • Java

  • Kotlin

ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
context.setBeanResolver(new MyBeanResolver());

// This will end up calling resolve(context, "&someFactoryBean") on
// MyBeanResolver during evaluation.
Object factoryBean = parser.parseExpression("&someFactoryBean").getValue(context);
val parser = SpelExpressionParser()
val context = StandardEvaluationContext()
context.setBeanResolver(MyBeanResolver())

// This will end up calling resolve(context, "&someFactoryBean") on
// MyBeanResolver during evaluation.
val factoryBean = parser.parseExpression("&someFactoryBean").getValue(context)