java 动态语言,使用Java配置中的Spring动态语言支持

I'd like to use Dynamic Languages Support of Spring Framework.

In XML I'd just use the lang namespace, but I'd like to use Java configuration (i.e. @Configuration classes) only.

I can imagine that I can do it by initializing all the hell from org.springframework.scripting.config package, inc. all the BeanPostProcessors, Handlers, Parsers and FactoryBeans they create, but I really don't want to go there.

Is there some other way? If there's none, what will be the minimal configuration needed to create a reloadable bean out of a Groovy script?

解决方案

Why don't you ask us directly by email? :-)

I see that XML Lang support is relly magic. There is enough stuff which is based on BeanDefinition and its attributes. In additional there are some hooks with ProxyFactory and CGLIB for the lang:property.

What I see for the JavaConfig is some Java class wrapper for the ScriptEvaluator and RefreshableResourceScriptSource from Spring Integration:

@ContextConfiguration

@RunWith(SpringJUnit4ClassRunner.class)

public class RefreshableScriptJavaConfigTests {

@Autowired

private Calculator calculator;

@Test

public void testGroovyRefreshableCalculator() {

assertEquals(5, this.calculator.add(2, 3));

}

@Configuration

public static class ContextConfiguration {

@Value("classpath:org/springframework/integration/scripting/config/jsr223/Calculator.groovy")

private Resource groovyScriptResource;

@Bean

public ScriptEvaluator groovyScriptEvaluator() {

return new GroovyScriptEvaluator();

}

@Bean

public Calculator calculator() {

return new Calculator(new RefreshableResourceScriptSource(this.groovyScriptResource, 1000));

}

}

public static class Calculator {

private final ScriptSource scriptSource;

@Autowired

private ScriptEvaluator scriptEvaluator;

public Calculator(ScriptSource scriptSource) {

this.scriptSource = scriptSource;

}

public int add(int x, int y) {

Map params = new HashMap();

params.put("x", x);

params.put("y", y);

return (int) this.scriptEvaluator.evaluate(this.scriptSource, params);

}

}

}

Where the Calculator.groovy is:

x + y

I understand that it isn't so flexible as it looks with interfaces and configuration from XML definition, but at least it will help you to see where we are.

Feel free to raise a JIRA issue on the matter and we'll see what we can do here. Something like @EnableScripting and @ScriptSource(refreshDelay = 1000) on the Resource @Bean method.

I think for now you can just @Import some XML snippets with lang definitions.

Cheers,

Artem

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值