Reputation: 319
SpEL is excellent feature provided by Spring, but sometimes, it is a little tedious to use SpEL to call a class constructors, this is a example
<bean id="plainPojo" class="myPackage.PoJo">
<property name="date" value="#{new java.util.Date()}"/>
</bean>
In order to initiate a Date
instance, I have to include the fully-qualified name of the Date
class. Is there a way that I can define a customize SpEL parser so that I don't have to write the fully-qualified name of the class I want to use?
By the way, it is OK to write SpEL like this:
<bean id="plainPojo" class="myPackage.PoJo">
<property name="name" value="#{new String('myName')}"/>
</bean>
The String class is in the java.lang package, so I think the default SpEL parser the Spring framework used has already include the path java.lang
.
Upvotes: 1
Views: 3119
Reputation: 327
To complement Gary's answer:
You can customize the evaluation context used when wiring beans (#{...}) by injecting a custom BeanExpressionResolver into the application context's bean factory. Subclass StandardBeanExpressionResolver and override customizeEvaluationContext() before refresh() ing the context.
This can be achieved by writing a BeanFactoryPostProcessor like below:
public class CustomBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
beanFactory.setBeanExpressionResolver(new CustomBeanExpressionResolver());
}
}
The BeanFactoryPostProcessor will get picked up automatically by Spring if you register it as a bean.
Upvotes: 0
Reputation: 174729
When using SpEL programmatically, you can inject a StandardTypeLocator
into the evaluation context, after adding your packages to the StandardTypeLocator
using registerImport()
. (That's how you would do it when using SpEL in Spring Integration flows). It does make it more convenient when using custom classes in SpEL expressions.
We use the technique in the twitter endpoints.
Same thing when using custom functions - they have to be registered with the evaluation context.
You can customize the evaluation context used when wiring beans (#{...}
) by injecting a custom BeanExpressionResolver
into the application context's bean factory. Subclass StandardBeanExpressionResolver
and override customizeEvaluationContext()
before refresh()
ing the context.
Upvotes: 2