Spring中集成Groovy的四種方式(小結(jié))
groovy是一種動(dòng)態(tài)腳本語言,適用于一些可變、和規(guī)則配置性的需求,目前Spring提供ScriptSource接口,支持兩種類型,一種是
ResourceScriptSource,另一種是 StaticScriptSource,但是有的場(chǎng)景我們需要把groovy代碼放進(jìn)DB中,所以我們需要擴(kuò)展這個(gè)。

ResourceScriptSource:在 resources 下面寫groovy類
StaticScriptSource:把groovy類代碼放進(jìn)XML里
DatabaseScriptSource:把groovy類代碼放進(jìn)數(shù)據(jù)庫中
工程模塊為:

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實(shí)現(xiàn)類

package com.maple.resource.groovy
class 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://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:lang="http://www.springframework.org/schema/lang"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/lang
http://www.springframework.org/schema/lang/spring-lang.xsd">
<lang:groovy id="helloService" script-source="classpath:groovy/HelloServiceImpl.groovy">
<lang:property name="name" value="maple"></lang:property>
</lang:groovy>
</beans>
主類 GroovyResourceApplication
package com.maple.resource;
import com.maple.resource.groovy.HelloService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.support.ClassPathXmlApplicationContext;
@SpringBootApplication
public class GroovyResourceApplication {
public static void main(String[] args) {
//SpringApplication.run(GroovyResourceApplication.class, args);
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-groovy.xml");
HelloService bean = context.getBean(HelloService.class);
String sayHello = bean.sayHello();
System.out.println(sayHello);
}
}
啟動(dòng)并測(cè)試

StaticScriptSource
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.groovy.staticscript.groovy;
/**
* @author: maple
* @version: HelloService.java, v 0.1 2020年09月25日 21:26 maple Exp $
*/
public interface HelloService {
String sayHello();
}
在spring-groovy.xml中配置具體的實(shí)現(xiàn)類
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:lang="http://www.springframework.org/schema/lang"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/lang
http://www.springframework.org/schema/lang/spring-lang.xsd">
<lang:groovy id="helloService">
<lang:inline-script>
import com.maple.groovy.staticscript.groovy.HelloService
class HelloServiceImpl implements HelloService {
String name;
@Override
String sayHello() {
return "Hello $name. Welcome to static script in Groovy.";
}
}
</lang:inline-script>
<lang:property name="name" value="maple"/>
</lang:groovy>
</beans>
主類 GroovyStaticscriptApplication
package com.maple.groovy.staticscript;
import com.maple.groovy.staticscript.groovy.HelloService;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.support.ClassPathXmlApplicationContext;
@SpringBootApplication
public class GroovyStaticscriptApplication {
public static void main(String[] args) {
//SpringApplication.run(GroovyStaticscriptApplication.class, args);
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-groovy.xml");
HelloService bean = context.getBean(HelloService.class);
String sayHello = bean.sayHello();
System.out.println(sayHello);
}
}
啟動(dòng)并測(cè)試

DatabaseScriptSource
下面我們先建表,把基本工作做完,這里我使用mybatisplus,dao、service等代碼省略
CREATE TABLE `groovy_script` ( `id` BIGINT ( 20 ) NOT NULL AUTO_INCREMENT, `script_name` VARCHAR ( 64 ) NOT NULL COMMENT 'script name', `script_content` text NOT NULL COMMENT 'script content', `status` VARCHAR ( 16 ) NOT NULL DEFAULT 'ENABLE' COMMENT 'ENABLE/DISENABLE', `extend_info` VARCHAR ( 4096 ) DEFAULT NULL, `created_time` TIMESTAMP ( 6 ) NOT NULL DEFAULT CURRENT_TIMESTAMP ( 6 ), `modified_time` TIMESTAMP ( 6 ) NOT NULL DEFAULT CURRENT_TIMESTAMP ( 6 ) ON UPDATE CURRENT_TIMESTAMP ( 6 ), PRIMARY KEY ( `id` ) ) ENGINE = INNODB AUTO_INCREMENT = 1 DEFAULT CHARSET = utf8mb4 COMMENT = 'groovy script';
INSERT INTO `gane-platform`.`groovy_script`(`id`, `script_name`, `script_content`, `status`, `extend_info`, `created_time`, `modified_time`) VALUES (1, 'helloService', 'package com.maple.resource.groovy\r\n\r\nimport com.maple.database.groovy.HelloService\r\n\r\npublic class HelloServiceImpl implements HelloService {\r\n\r\n @Override\r\n String sayHello(String name) {\r\n return \"Hello \"+name+\". Welcome to database in Groovy.\";\r\n }\r\n}', 'ENABLE', NULL, '2020-09-26 17:16:36.477818', '2020-09-27 08:23:10.790553');
方法一:
1、實(shí)時(shí)讀取DB里的groovy腳本文件
2、利用GroovyClassLoader去編譯腳本文件
3、把class對(duì)象注入成Spring bean
4、反射調(diào)用腳本的方法
package com.maple.database.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.maple.database.entity.GroovyScript;
import com.maple.database.groovy.SpringContextUtils;
import com.maple.database.service.GroovyScriptService;
import groovy.lang.GroovyClassLoader;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* @author: maple
* @version: GroovyController.java, v 0.1 2020年09月26日 17:18 maple Exp $
*/
@RestController
public class GroovyController {
@Resource
private GroovyScriptService groovyScriptService;
@GetMapping("/groovyTest")
private String groovyTest() throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException {
GroovyScript groovyScript = groovyScriptService.getOne(new QueryWrapper<GroovyScript>()
.eq("script_name", "helloService").eq("status", "ENABLE"));
System.out.println(groovyScript.getScriptContent());
Class clazz = new GroovyClassLoader().parseClass(groovyScript.getScriptContent());
Object o = clazz.newInstance();
SpringContextUtils.autowireBean(o);
Method method = clazz.getMethod("sayHello", String.class);
return (String) method.invoke(o, "maple");
}
}
package com.maple.database.groovy;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* @author: maple
* @version: SpringContextUtils.java, v 0.1 2020年09月26日 17:29 maple Exp $
*/
@Component
public class SpringContextUtils implements ApplicationContextAware {
static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextUtils.context = applicationContext;
}
public static void autowireBean(Object bean) {
context.getAutowireCapableBeanFactory().autowireBean(bean);
}
public static ApplicationContext getContext() {
return context;
}
public static <T> T getBean(Class<T> clazz) {
return context.getBean(clazz);
}
public static <T> T getBean(String name) {
return (T) context.getBean(name);
}
}
啟動(dòng)測(cè)試結(jié)果為:

總結(jié):
優(yōu)點(diǎn):實(shí)時(shí)讀取DB里的腳本,當(dāng)腳本更改時(shí),可以直接修改DB,對(duì)代碼無侵入
缺點(diǎn):每次都要查詢DB,反射調(diào)用代碼寫死了
方法二:
1、我們模仿groovy-resource的思路,resource的XML配置是下面這樣的
<lang:groovy id="helloService" script-source="classpath:groovy/HelloServiceImpl.groovy" />
所以,我們可以把DatabaseScriptSource的XML保存成這種格式
<lang:groovy id="helloService" script-source="database:helloService"/>
2、然后模仿Spring保存成XML格式的document的思路,我們也把groovy保存成XML格式的document,放進(jìn)內(nèi)存里
3、groovy的關(guān)鍵處理類是ScriptFactoryPostProcessor,當(dāng) Spring 裝載應(yīng)用程序上下文時(shí),它首先創(chuàng)建工廠 bean(例如 GroovyScriptFactory bean)。然后,執(zhí)行ScriptFactoryPostProcessor bean,用實(shí)際的腳本對(duì)象替換所有的工廠 bean。例如,我們本次測(cè)試的配置產(chǎn)生一個(gè)名為 helloService 的 bean,它的類型是groovierspring.GroovyHelloService。(如果啟用 Spring 中的 debug 級(jí)日志記錄,并觀察應(yīng)用程序上下文的啟動(dòng),將會(huì)看到 Spring 首先創(chuàng)建一個(gè)名為 scriptFactory.helloService 的工廠 bean,然后 ScriptFactoryPostProcessor 從該工廠 bean 創(chuàng)建 helloService bean)。
我們發(fā)現(xiàn)ScriptFactoryPostProcessor這個(gè)類中,有g(shù)etScriptSource這個(gè)方法,該方法里有convertToScriptSource方法


在convertToScriptSource這個(gè)方法中,他默認(rèn)支持我們前面說過的static script和resource兩種類型,但是現(xiàn)在我們新增了一種database類型,所以我們需要重寫該方法,其他的工作都一樣,交給ScriptFactoryPostProcessor幫我們?nèi)ヌ幚怼?/p>
package com.maple.database.manage;
import com.maple.database.groovy.DatabaseScriptSource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ResourceLoader;
import org.springframework.scripting.ScriptSource;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.scripting.support.ScriptFactoryPostProcessor;
import org.springframework.scripting.support.StaticScriptSource;
import org.springframework.stereotype.Component;
/**
* @author: maple
* @version: CustomerScriptFactoryPostProcessor.java, v 0.1 2020年09月26日 20:36 maple Exp $
*/
@Component
public class CustomerScriptFactoryPostProcessor extends ScriptFactoryPostProcessor {
@Override
protected ScriptSource convertToScriptSource(String beanName, String scriptSourceLocator, ResourceLoader resourceLoader) {
if (scriptSourceLocator.startsWith(INLINE_SCRIPT_PREFIX)) {
return new StaticScriptSource(scriptSourceLocator.substring(INLINE_SCRIPT_PREFIX.length()), beanName);
}
if (scriptSourceLocator.startsWith(GroovyConstant.SCRIPT_SOURCE_PREFIX)) {
return new DatabaseScriptSource(StringUtils.substringAfter(scriptSourceLocator, GroovyConstant.SCRIPT_SOURCE_PREFIX));
}
return new ResourceScriptSource(resourceLoader.getResource(scriptSourceLocator));
}
}
但是我們也要看看ScriptFactoryPostProcessor幫我們處理的其他工作都是什么:
(1)predictBeanType:是 Spring 中從 BeanDefinition 中提取 Bean 類型的底層 API

(2)我們?cè)賮砜磒repareScriptBeans準(zhǔn)備了什么

(3)scriptBeanFactory.registerBeanDefinition,向beanDefinitionMap里put鍵值對(duì)


(4)createScriptedObjectBeanDefinition

(5)Class<?> scriptedType = scriptFactory.getScriptedObjectType(scriptSource);
這句是為了拿到我們具體的實(shí)現(xiàn)類,也是我們的基礎(chǔ),它里面就是用GroovyClassLoader去編譯我們的groovy腳本內(nèi)容,并返回了Class<?> scriptClass我們的HelloServiceImpl

(6)ScriptSource scriptSource = getScriptSource(scriptFactoryBeanName, scriptFactory.getScriptSourceLocator());

這里首先去我們下面新增的DatabaseScriptSource里拿到groovy腳本內(nèi)容,并放進(jìn)map里,返回DatabaseScriptSource
4、新增DatabaseScriptSource類
package com.maple.database.groovy;
import com.maple.database.groovy.cache.GroovyCache;
import org.springframework.scripting.ScriptSource;
import org.springframework.util.StringUtils;
import java.io.IOException;
/**
* @author: maple
* @version: DatabaseScriptSource.java, v 0.1 2020年09月26日 15:37 maple Exp $
*/
public final class DatabaseScriptSource implements ScriptSource {
/**
* 腳本名稱
*/
private String scriptName;
/**
* 構(gòu)造函數(shù)
*
* @param scriptName
*/
public DatabaseScriptSource(String scriptName) {
this.scriptName = scriptName;
}
@Override
public String getScriptAsString() throws IOException {
return GroovyCache.getByName(scriptName).getGroovyContent();
}
@Override
public boolean isModified() {
return false;
}
@Override
public String suggestedClassName() {
return StringUtils.stripFilenameExtension(this.scriptName);
}
}
5、把我們的CustomerScriptFactoryPostProcessor放進(jìn)Spring的List<BeanPostProcessor>中

這樣的話,我們就能從Spring容器中獲取helloService的bean實(shí)例了,測(cè)試:
package com.maple.database.controller;
import com.maple.database.groovy.HelloService;
import com.maple.database.groovy.SpringContextUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author: maple
* @version: GroovyController.java, v 0.1 2020年09月26日 17:18 maple Exp $
*/
@RestController
public class NewGroovyController {
@GetMapping("/newGroovyTest")
private String newGroovyTest() {
HelloService helloService = SpringContextUtils.getBean("helloService");
String hello = helloService.sayHello("maple");
System.out.println(hello);
return hello;
}
}

總結(jié):
優(yōu)點(diǎn):項(xiàng)目初始化的時(shí)候,就把DB里的groovy腳本讀取到,放進(jìn)本次緩存里,并交給Spring管理,減少與DB的交互次數(shù);沒有硬編碼,擴(kuò)展性更好。
缺點(diǎn):當(dāng)DB里的groovy腳本文件需要修改時(shí),我們改完之后不能立即生效,需要重啟工程或者刷新本次緩存,再次放進(jìn)Spring容器里才行
附上核心處理類:GroovyDynamicLoader
package com.maple.database.manage;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.maple.database.entity.GroovyScript;
import com.maple.database.groovy.cache.GroovyCache;
import com.maple.database.groovy.cache.GroovyInfo;
import com.maple.database.service.GroovyScriptService;
import groovy.lang.GroovyClassLoader;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.xml.ResourceEntityResolver;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author: maple
* @version: GroovyDynamicLoader.java, v 0.1 2020年09月26日 20:00 maple Exp $
*/
@Configuration
public class GroovyDynamicLoader implements ApplicationContextAware, InitializingBean {
private ConfigurableApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = (ConfigurableApplicationContext) applicationContext;
}
@Resource
private GroovyScriptService groovyScriptService;
private static final GroovyClassLoader groovyClassLoader = new GroovyClassLoader(GroovyDynamicLoader.class.getClassLoader());
@Override
public void afterPropertiesSet() throws Exception {
init();
}
private void init() {
List<GroovyScript> groovyScripts = groovyScriptService.list(new QueryWrapper<GroovyScript>().eq("status", "ENABLE"));
List<GroovyInfo> groovyInfos = groovyScripts.stream().map(groovyScript -> {
GroovyInfo groovyInfo = new GroovyInfo();
groovyInfo.setClassName(groovyScript.getScriptName());
groovyInfo.setGroovyContent(groovyScript.getScriptContent());
return groovyInfo;
}).collect(Collectors.toList());
if (CollectionUtils.isEmpty(groovyInfos)) {
return;
}
ConfigurationXMLWriter config = new ConfigurationXMLWriter();
addConfiguration(config, groovyInfos);
GroovyCache.put2map(groovyInfos);
loadBeanDefinitions(config);
}
private void addConfiguration(ConfigurationXMLWriter config, List<GroovyInfo> groovyInfos) {
for (GroovyInfo groovyInfo : groovyInfos) {
writeBean(config, groovyInfo);
}
}
private void writeBean(ConfigurationXMLWriter config, GroovyInfo groovyInfo) {
if (checkSyntax(groovyInfo)) {
DynamicBean bean = composeDynamicBean(groovyInfo);
config.write(GroovyConstant.SPRING_TAG, bean);
}
}
private boolean checkSyntax(GroovyInfo groovyInfo) {
try {
groovyClassLoader.parseClass(groovyInfo.getGroovyContent());
} catch (Exception e) {
return false;
}
return true;
}
private DynamicBean composeDynamicBean(GroovyInfo groovyInfo) {
DynamicBean bean = new DynamicBean();
String scriptName = groovyInfo.getClassName();
Assert.notNull(scriptName, "parser className cannot be empty!");
//設(shè)置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));
}
}
}
到此這篇關(guān)于Spring中集成Groovy的四種方式(小結(jié))的文章就介紹到這了,更多相關(guān)Spring集成Groovy內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Springboot整合Druid實(shí)現(xiàn)對(duì)訪問的監(jiān)控方式
這篇文章主要介紹了Springboot整合Druid實(shí)現(xiàn)對(duì)訪問的監(jiān)控方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-05-05
詳解Spring Cloud Netflix Zuul中的速率限制
這篇文章主要介紹了詳解Spring Cloud Netflix Zuul中的速率限制,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-11-11
學(xué)會(huì)在Java中使用Optional功能
這篇文章主要介紹了學(xué)會(huì)在Java中使用Optional功能,在本文中,我們將了解如何、何時(shí)以及在哪里最好地應(yīng)用Optional,具體相關(guān)內(nèi)容需要的朋友可以參考下面文章內(nèi)容2022-09-09
JavaCV簡(jiǎn)介與環(huán)境搭建詳細(xì)步驟
JavaCV是一個(gè)開源的Java接口,它為幾個(gè)著名的計(jì)算機(jī)視覺庫(如OpenCV、FFmpeg)提供了Java封裝,這篇文章主要給大家介紹了關(guān)于JavaCV簡(jiǎn)介與環(huán)境搭建的相關(guān)資料,需要的朋友可以參考下2024-04-04
MQ的分類組成優(yōu)缺點(diǎn)測(cè)試點(diǎn)入門教程
這篇文章主要為大家介紹了MQ的分類組成優(yōu)缺點(diǎn)測(cè)試點(diǎn)入門教程,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05
Spring Cloud 的 Hystrix.功能及實(shí)踐詳解
這篇文章主要介紹了Spring Cloud 的 Hystrix.功能及實(shí)踐詳解,Hystrix 具備服務(wù)降級(jí)、服務(wù)熔斷、線程和信號(hào)隔離、請(qǐng)求緩存、請(qǐng)求合并以及服務(wù)監(jiān)控等強(qiáng)大功能,需要的朋友可以參考下2019-07-07

