Java調(diào)用groovy實現(xiàn)原理代碼實例
一、概述
Groovy is a multi-faceted language for the Java platform.
Apache Groovy是一種強大的、可選的類型化和動態(tài)語言,具有靜態(tài)類型和靜態(tài)編譯功能,用于Java平臺,目的在于通過簡潔、熟悉和易于學習的語法提高開發(fā)人員的工作效率。它可以與任何Java程序順利集成,并立即向您的應(yīng)用程序提供強大的功能,包括腳本編寫功能、特定于域的語言編寫、運行時和編譯時元編程以及函數(shù)式編程。
Groovy是基于java虛擬機的,執(zhí)行文件可以是簡單的腳本片段,也可以是一個完整的groovy class,對于java程序員來說,學習成本低,可以完全用java語法編寫。
二、java項目執(zhí)行g(shù)roovy必要環(huán)境
<dependency> <groupId>org.codehaus.groovy</groupId> <artifactId>groovy-all</artifactId> <version>2.4.16</version> </dependency> <dependency> <groupId>org.kohsuke</groupId> <artifactId>groovy-sandbox</artifactId> <version>1.7</version> </dependency>
三、java項目執(zhí)行g(shù)roovy方式
3.1 ScriptEngineManager
groovy遵循JSR 223標準,可以使用jdk的標準接口ScriptEngineManager調(diào)用。
@org.junit.Test public void scriptEngineManager() throws ScriptException, NoSuchMethodException { ScriptEngineManager factory = new ScriptEngineManager(); // 每次生成一個engine實例 ScriptEngine engine = factory.getEngineByName("groovy"); System.**out**.println(engine.toString()); // javax.script.Bindings Bindings binding = engine.createBindings(); binding.put("date", new Date()); // 如果script文本來自文件,請首先獲取文件內(nèi)容 engine.eval("def getTime(){return date.getTime();}", binding); engine.eval("def sayHello(name,age){return 'Hello,I am ' + name + ',age' + age;}"); Long time = (Long) ((Invocable) engine).invokeFunction("getTime", null);// 反射到方法 System.**out**.println(time); String message = (String) ((Invocable) engine).invokeFunction("sayHello", "zhangsan", 12); System.**out**.println(message); }
((Invocable) engine).invokeFunction(方法名,…參數(shù))
3.2 GroovyShell
直接使用GroovyShell,執(zhí)行g(shù)roovy腳本片段,GroovyShell每一次執(zhí)行時代碼時會動態(tài)將代碼編譯成java class,然后生成java對象在java虛擬機上執(zhí)行,所以如果使用GroovyShell會造成class太多,性能較差。
@org.junit.Test public void testGroovyShell() { final String script = "Runtime.getRuntime().availableProcessors()"; Binding intBinding = new Binding(); GroovyShell shell = new GroovyShell(intBinding); final Object eval = shell.evaluate(script); System.**out**.println(eval); }
3.3 GroovyClassLoader
groovy官方提供GroovyClassLoader從文件,url或字符串中加載解析Groovy class
@org.junit.Test public void testGroovyClassLoader() throws IllegalAccessException, InstantiationException { GroovyClassLoader groovyClassLoader = new GroovyClassLoader(); String hello = "package com.szwn.util" + "class GroovyHello {" + "String sayHello(String name) {" + "print 'GroovyHello call'" + "name" + "}" + "}"; Class aClass = groovyClassLoader.parseClass(hello); GroovyObject object = (GroovyObject) aClass.newInstance(); Object o = object.invokeMethod("sayHello", "zhangsan"); System.out.println(o.toString()); }
3.4 GroovyScriptEngine
GroovyScriptEngine可以從url(文件夾,遠程協(xié)議地址,jar包)等位置動態(tài)加裝resource(script或則Class),同時對
編譯后的class字節(jié)碼進行了緩存,當文件內(nèi)容更新或者文件依賴的類更新時,會自動更新緩存。
@org.junit.Test public void testGroovyScriptEngine() throws IOException, ResourceException, groovy.util.ScriptException { String url = "...(文件地址)"; GroovyScriptEngine engine = new GroovyScriptEngine(url); for (int i = 0; i < 5; i++) { Binding binding = new Binding(); binding.setVariable("index", i); // 每一次執(zhí)行獲取緩存Class,創(chuàng)建新的Script對象 Object run = engine.run("HelloWorld.groovy", binding); System.out.println(run); } }
四、安全
4.1 SecureASTCustomizer
Groovy會自動引入java.util,java.lang包,方便用戶調(diào)用,但同時也增加了系統(tǒng)的風險。為了防止用戶調(diào)用System.exit或Runtime等方法導(dǎo)致系統(tǒng)宕機,以及自定義的groovy片段代碼執(zhí)行死循環(huán)或調(diào)用資源超時等問題,Groovy提供了SecureASTCustomizer安全管理者和SandboxTransformer沙盒環(huán)境。
@org.junit.Test public void testAST() { final String script = "import com.alibaba.fastjson.JSONObject;JSONObject object = new JSONObject()"; // 創(chuàng)建SecureASTCustomizer final SecureASTCustomizer secure = new SecureASTCustomizer(); // 禁止使用閉包 secure.setClosuresAllowed(true); List<Integer> tokensBlacklist = new ArrayList<>(); // 添加關(guān)鍵字黑名單 while和goto tokensBlacklist.add(Types.**KEYWORD_WHILE**); tokensBlacklist.add(Types.**KEYWORD_GOTO**); secure.setTokensBlacklist(tokensBlacklist); // 設(shè)置直接導(dǎo)入檢查 secure.setIndirectImportCheckEnabled(true); // 添加導(dǎo)入黑名單,用戶不能導(dǎo)入JSONObject List<String> list = new ArrayList<>(); list.add("com.alibaba.fastjson.JSONObject"); secure.setImportsBlacklist(list); // statement 黑名單,不能使用while循環(huán)塊 List<Class<? extends Statement>> statementBlacklist = new ArrayList<>(); statementBlacklist.add(WhileStatement.class); secure.setStatementsBlacklist(statementBlacklist); // 自定義CompilerConfiguration,設(shè)置AST final CompilerConfiguration config = new CompilerConfiguration(); config.addCompilationCustomizers(secure); Binding intBinding = new Binding(); GroovyShell shell = new GroovyShell(intBinding, config); final Object eval = shell.evaluate(script); System.out.println(eval); }
SecureASTCustomizer :屬性
tokensBlacklist 關(guān)鍵字黑名單
ImportsBlacklist 導(dǎo)入黑名單
statementBlacklist statement 黑名單
如果代碼塊中出現(xiàn)黑名單限制的內(nèi)容,則會拋出異常
4.2 SandboxTransformer
用戶調(diào)用System.exit或調(diào)用Runtime的所有靜態(tài)方法都會拋出SecurityException
@org.junit.Test public void testGroovySandbox() { // 自定義配置 CompilerConfiguration config = new CompilerConfiguration(); // 添加線程中斷攔截器,可攔截循環(huán)體(for,while)、方法和閉包的首指令 config.addCompilationCustomizers(new ASTTransformationCustomizer(ThreadInterrupt.class)); // 添加線程中斷攔截器,可中斷超時線程,當前定義超時時間為3s Map<String, Object> timeoutArgs = new HashMap<>(); timeoutArgs.put("value", 3); config.addCompilationCustomizers(new ASTTransformationCustomizer(timeoutArgs, TimedInterrupt.class)); // 沙盒環(huán)境 config.addCompilationCustomizers(new SandboxTransformer()); GroovyShell sh = new GroovyShell(config); // 注冊至當前線程 new NoSystemExitSandbox().register(); new NoRunTimeSandbox().register(); // 確保在每次更新緩存Class<Script>對象時候,采用不同的groovyClassLoader Script groovyScript = sh.parse("System.exit(1)"); Object run = groovyScript.run(); System.**out**.println(run); } class NoSystemExitSandbox extends GroovyInterceptor { @Override public Object onStaticCall(GroovyInterceptor.Invoker invoker, Class receiver, String method, Object... args) throws Throwable { if (receiver == System.class && method.equals("exit")) { throw new SecurityException("No call on System.exit() please"); } return super.onStaticCall(invoker, receiver, method, args); } } class NoRunTimeSandbox extends GroovyInterceptor { @Override public Object onStaticCall(GroovyInterceptor.Invoker invoker, Class receiver, String method, Object... args) throws Throwable { if (receiver == Runtime.class) { throw new SecurityException("No call on RunTime please"); } return super.onStaticCall(invoker, receiver, method, args); } }
五、groovy代碼塊調(diào)用java代碼注意事項
5.1 java代碼行/代碼塊
Java代碼可以直接放在groovy方法體/代碼塊中運行
def hello = {name ->
System.out.println(name)
}
等同于
def helli = {name ->
println(name)
}
5.2 獲取java對象
5.2.1 new
直接通過new 來獲取
def newJavaObject(){ DpDeptCopyInfo deptCopyInfo = new DpDeptCopyInfo(); println(deptCopyInfo) } newJavaObject();
5.2.2 spring bean
不能使用@Autowired(autowired是在spring啟動后注入的,此時還未加載groovy代碼,故無法注入)
建議實現(xiàn)ApplicationContextAware接口的工具(組件)來獲取spring bean
@Component public final class SpringUtils implements BeanFactoryPostProcessor { /** Spring應(yīng)用上下文環(huán)境 \*/ private static ConfigurableListableBeanFactory beanFactory; @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { SpringUtils.beanFactory = beanFactory; } @SuppressWarnings("unchecked") public static <T> T getBean(String name) throws BeansException { return (T) beanFactory.getBean(name); } public static <T> T getBean(Class<T> clz) throws BeansException { T result = (T) beanFactory.getBean(clz); return result; } }
例:
被調(diào)用的groovy代碼
def springTransfer = {name -> println("==============================開始groovy====================================") QueryDataDaoService daoService = SpringUtils.getBean(QueryDataDaoService.class); println("對象:" + daoService) println("==============================結(jié)束groovy====================================") println("==============================返回傳入?yún)?shù)====================================") return name } springTransfer(name)
Java代碼:
@Test public void testGroovySpringTransfer() throws IOException, ResourceException, ScriptException { //獲取 groovy腳本文件的絕對路徑 String filePath = "文件路徑"; GroovyScriptEngine engine = new GroovyScriptEngine(filePath); //執(zhí)行獲取緩存Class,創(chuàng)建新的Script對象 Object run = engine.run("SpringTransfer.groovy", "ladq"); System.out.println("執(zhí)行g(shù)roovy結(jié)果:" + run); }
執(zhí)行結(jié)果
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot Session共享實現(xiàn)圖解
這篇文章主要介紹了SpringBoot Session共享實現(xiàn)圖解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-01-01使用feign調(diào)用接口時調(diào)不到get方法的問題及解決
這篇文章主要介紹了使用feign調(diào)用接口時調(diào)不到get方法的問題及解決,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03Java中遍歷Map的多種方法示例及優(yōu)缺點總結(jié)
在java中遍歷Map有不少的方法,下面這篇文章主要給大家介紹了關(guān)于Java中遍歷Map的多種方法,以及各種方法的優(yōu)缺點總結(jié),文中通過示例代碼介紹的非常詳細,對大家具有一定的參考學習價值,需要的朋友們下面來一起看看吧。2017-07-07SpringBoot EasyPoi動態(tài)導(dǎo)入導(dǎo)出的兩種方式實現(xiàn)方法詳解
項目里使用的是EasyPoi來處理導(dǎo)入導(dǎo)出功能的。近日因業(yè)務(wù)需求調(diào)整,一些導(dǎo)出功能的導(dǎo)出列需要根據(jù)不同的條件動態(tài)導(dǎo)出2022-09-09Java的DataInputStream和DataOutputStream數(shù)據(jù)輸入輸出流
這里我們來看一下Java的DataInputStream和DataOutputStream數(shù)據(jù)輸入輸出流的使用示例,兩個類分別繼承于FilterInputStream和FilterOutputStream:2016-06-06SpringBoot?ScheduledTaskRegistrar解決動態(tài)定時任務(wù)思路詳解
本文將從問題出發(fā),詳細介紹ScheduledTaskRegistrar類是如何解決動態(tài)調(diào)整定時任務(wù)的思路,并給出關(guān)鍵的代碼示例,幫助大家快速地上手學習2023-02-02