Spring中集成Groovy的四種方式(小結)
groovy是一種動態(tài)腳本語言,適用于一些可變、和規(guī)則配置性的需求,目前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.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); } }
啟動并測試
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中配置具體的實現類
<?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); } }
啟動并測試
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、實時讀取DB里的groovy腳本文件
2、利用GroovyClassLoader去編譯腳本文件
3、把class對象注入成Spring bean
4、反射調用腳本的方法
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); } }
啟動測試結果為:
總結:
優(yōu)點:實時讀取DB里的腳本,當腳本更改時,可以直接修改DB,對代碼無侵入
缺點:每次都要查詢DB,反射調用代碼寫死了
方法二:
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,放進內存里
3、groovy的關鍵處理類是ScriptFactoryPostProcessor,當 Spring 裝載應用程序上下文時,它首先創(chuàng)建工廠 bean(例如 GroovyScriptFactory bean)。然后,執(zhí)行ScriptFactoryPostProcessor bean,用實際的腳本對象替換所有的工廠 bean。例如,我們本次測試的配置產生一個名為 helloService 的 bean,它的類型是groovierspring.GroovyHelloService。(如果啟用 Spring 中的 debug 級日志記錄,并觀察應用程序上下文的啟動,將會看到 Spring 首先創(chuàng)建一個名為 scriptFactory.helloService 的工廠 bean,然后 ScriptFactoryPostProcessor 從該工廠 bean 創(chuàng)建 helloService bean)。
我們發(fā)現ScriptFactoryPostProcessor這個類中,有getScriptSource這個方法,該方法里有convertToScriptSource方法
在convertToScriptSource這個方法中,他默認支持我們前面說過的static script和resource兩種類型,但是現在我們新增了一種database類型,所以我們需要重寫該方法,其他的工作都一樣,交給ScriptFactoryPostProcessor幫我們去處理。
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)我們再來看prepareScriptBeans準備了什么
(3)scriptBeanFactory.registerBeanDefinition,向beanDefinitionMap里put鍵值對
(4)createScriptedObjectBeanDefinition
(5)Class<?> scriptedType = scriptFactory.getScriptedObjectType(scriptSource);
這句是為了拿到我們具體的實現類,也是我們的基礎,它里面就是用GroovyClassLoader去編譯我們的groovy腳本內容,并返回了Class<?> scriptClass我們的HelloServiceImpl
(6)ScriptSource scriptSource = getScriptSource(scriptFactoryBeanName, scriptFactory.getScriptSourceLocator());
這里首先去我們下面新增的DatabaseScriptSource里拿到groovy腳本內容,并放進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; /** * 構造函數 * * @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放進Spring的List<BeanPostProcessor>中
這樣的話,我們就能從Spring容器中獲取helloService的bean實例了,測試:
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; } }
總結:
優(yōu)點:項目初始化的時候,就把DB里的groovy腳本讀取到,放進本次緩存里,并交給Spring管理,減少與DB的交互次數;沒有硬編碼,擴展性更好。
缺點:當DB里的groovy腳本文件需要修改時,我們改完之后不能立即生效,需要重啟工程或者刷新本次緩存,再次放進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!"); //設置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內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Springboot整合Druid實現對訪問的監(jiān)控方式
這篇文章主要介紹了Springboot整合Druid實現對訪問的監(jiān)控方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-05-05詳解Spring Cloud Netflix Zuul中的速率限制
這篇文章主要介紹了詳解Spring Cloud Netflix Zuul中的速率限制,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-11-11Spring Cloud 的 Hystrix.功能及實踐詳解
這篇文章主要介紹了Spring Cloud 的 Hystrix.功能及實踐詳解,Hystrix 具備服務降級、服務熔斷、線程和信號隔離、請求緩存、請求合并以及服務監(jiān)控等強大功能,需要的朋友可以參考下2019-07-07