groovy是一种动态脚本语言,适用于一些可变、和规则配置性的需求,目前Spring提供ScriptSource接口,支持两种类型,一种是
ResourceScriptSource,另一种是 StaticScriptSource,但是有的场景我们需要把groovy代码放进DB中,所以我们需要扩展这个。
ResourceScriptSource:在 resources 下面写groovy类
StaticScriptSource:把groovy类代码放进XML里
DatabaseScriptSource:把groovy类代码放进数据库中
工程模块为:
ResourceScriptSource
groovy的pom
<dependency> <artifactId>groovy-all</artifactId> <groupId>org.codehaus.groovy</groupId> <version>2.1.9</version> <scope>compile</scope> </dependency>HelloService接口
package com.maple.resource.groovy;/** * @author: maple * @version: HelloService.java, v 0.1 2020年09月25日 21:26 maple Exp $ */public interface HelloService { String sayHello();}resources下面建groovy实现类
package com.maple.resource.groovyclass HelloServiceImpl implements HelloService { String name; @Override String sayHello() { return "Hello $name. Welcome to resource in Groovy."; }}在spring-groovy.xml中配置
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://poseDynamicBean(GroovyInfo groovyInfo) { DynamicBean bean = new DynamicBean(); String scriptName = groovyInfo.getClassName(); Assert.notNull(scriptName, "parser className cannot be empty!"); //设置bean的属性,这里只有id和script-source。 bean.put("id", scriptName); bean.put("script-source", GroovyConstant.SCRIPT_SOURCE_PREFIX + scriptName); return bean; } private void loadBeanDefinitions(ConfigurationXMLWriter config) { String contextString = config.getContent(); if (StringUtils.isBlank(contextString)) { return; } XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader((BeanDefinitionRegistry) this.applicationContext.getBeanFactory()); beanDefinitionReader.setResourceLoader(this.applicationContext); beanDefinitionReader.setBeanClassLoader(applicationContext.getClassLoader()); beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this.applicationContext)); beanDefinitionReader.loadBeanDefinitions(new InMemoryResource(contextString)); String[] postProcessorNames = applicationContext.getBeanFactory().getBeanNamesForType(CustomerScriptFactoryPostProcessor.class, true, false); for (String postProcessorName : postProcessorNames) { applicationContext.getBeanFactory().addBeanPostProcessor((BeanPostProcessor) applicationContext.getBean(postProcessorName)); } }}到此这篇关于Spring中集成Groovy的四种方式(小结)的文章就介绍到这了,更多相关Spring集成Groovy内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!