溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

springboot怎么集成groovy腳本使用

發(fā)布時間:2022-04-07 14:37:43 來源:億速云 閱讀:381 作者:iii 欄目:編程語言

這篇文章主要講解了“springboot怎么集成groovy腳本使用”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“springboot怎么集成groovy腳本使用”吧!

在我們的應用中引入腳本能力,可以很好的提升靈活性,我們的核心開發(fā)工作可以集中在核心平臺能力的開發(fā)上,具體場景的功能可以通過腳本來實現,例如jenkins就可以通過groovy腳本來編寫pipeline,可以很靈活的定制構建過程。 spring本身提供了groovy集成的機制,分為兩種方式,一種是用groovy開發(fā)程序,跟用java開發(fā)類似,需要經過編譯。一種是將groovy作為腳本來執(zhí)行,不需要編譯。在此我們介紹的是第二種方式,將groovy作為腳本來使用。 

一、概述

在spring中集成groovy腳本,主要有2種思路,一種是在groovy腳本中定義bean,這樣groovy腳本就融入了整個spring的體系,跟使用普通的bean沒有區(qū)別。一種是在程序中調用groovy腳本,讓groovy腳本成為一個可執(zhí)行的部件。下面我們分別介紹這2種方式。 在spring中聲明groovy腳本中定義的bean有兩種方式,一種是傳統(tǒng)的xml,一種是spring-framework-4中引入的groovy聲明方式。

二、在groovy中定義bean

首先我們定義一個interface:

public interface MyService {
    String fun(MyDomain myDomain);
}

這兒提供了一種思路,我們可以用java代碼編寫默認的interface實現,如果默認實現不滿足特定場景的要求時,配合策略模式,用groovy腳本實現特定場景,程序會變的很靈活,配合腳本的熱加載機制,當處理邏輯需要變化時,在程序運行的過程中,我們可以隨時調整腳本內容且能夠及時生效。

在groovy腳本MyServiceImpl.groovy中實現這個interface:

class MyServiceImpl implements MyService {
    @Autowired
    FunBean useBean;

    String myProp;

    String fun(MyDomain myDomain) {
        return myDomain.toString() + useBean.getFunName() + myProp;
    }
}

下面分別介紹通過xml和groovy兩種配置方式來聲明bean。

2.1、通過xml配置的方式聲明groovy中實現的bean

通過xml配置聲明bean是spring傳統(tǒng)的方法,這種方法近來已經被通過java代碼聲明的方式取代,但是對于聲明groovy腳本中定義的bean來說還是最簡單的方法。

<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 https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/lang https://www.springframework.org/schema/lang/spring-lang.xsd">
    <lang:groovy id="myServiceXml" script-source="classpath:MyServiceImpl.groovy" refresh-check-delay="10000" >
        <lang:property name="myProp" value=" this is xml init prop" />
    </lang:groovy>
</beans>

以上xml代碼聲明了myServiceXml這個bean,script-source指定了這個bean的來源是classpath:MyServiceImpl.groovy這個腳本文件。將classpath替換為file,可以指定任一位置的腳本文件。
refresh-check-delay定義了腳本的刷新間隔,當腳本內容發(fā)生變化后,可以自動刷新腳本的內容。
lang:property這個標簽可以對bean的屬性進行初始化賦值。

我們分別用xml和groovy兩種聲明bean的方式給myProp這個屬性賦值不同的初始值,在后續(xù)的演示代碼中可以看到。

2.2、通過groovy配置的方式聲明groovy中實現的bean

spring-framework-4中引入了groovy聲明bean的方式,我們用groovy來聲明myServiceGroovy這個bean,相比于xml的方式,groovy的聲明方式可讀性更強一些。

詳細介紹見spring的官方博文: Groovy Bean Configuration in Spring Framework 4

import org.springframework.scripting.groovy.GroovyScriptFactory
import org.springframework.scripting.support.ScriptFactoryPostProcessor

beans {
    scriptFactoryPostProcessor(ScriptFactoryPostProcessor) {
        defaultRefreshCheckDelay = 10000
    }
    myServiceGroovy(GroovyScriptFactory, 'classpath:MyServiceImpl.groovy') {
        bean ->
            bean.scope = "prototype"
            myProp = ' this is Bean Builder init prop'
            bean.beanDefinition.setAttribute(ScriptFactoryPostProcessor.REFRESH_CHECK_DELAY_ATTRIBUTE, 6000)
    }
}

通過GroovyScriptFactory可以指定定義bean的groovy腳本位置。 通過bean的lambda表達式,可以對bean的屬性進行賦值,除了我們定義的myProp這個屬性外,還可以定義scope和腳本刷新時間。

2.3、調用groovy中實現的bean

前面我們通過xml和groovy兩種方式分別聲明了2個bean: myServiceXmlmyServiceGroovy,下面我們在程序中調用這2個bean。

@SpringBootApplication
@ImportResource({"classpath:xml-bean-config.xml", "classpath:BeanBuilder.groovy"})
public class Application implements CommandLineRunner {

    @Autowired
    private MyService myServiceXml;
    @Autowired
    private MyService myServiceGroovy;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    public void run(String... args) throws ScriptException, ResourceException, IllegalAccessException, InstantiationException {
        MyDomain myDomain = new MyDomain();
        myDomain.setName("test");
        System.out.println(myServiceXml.fun(myDomain));
        myDomain.setName("test2");
        System.out.println(myServiceGroovy.fun(myDomain));
    }
}

首先我們通過@ImportResource來引入bean的聲明文件,然后就是普通的bean的依賴注入和方法調用,可以看到在bean的使用上,腳本定義的bean和用程序編寫的bean沒有任何區(qū)別。 在run方法中,我們分別調用了myServiceXml和myServiceGroovy的這2個bean的fun方法。 執(zhí)行run方法可以看到輸出到結果:

MyDomain(name=test)FunBean this is xml init prop
MyDomain(name=test2)FunBean this is Bean Builder init prop

三、執(zhí)行groovy腳本

除了前面提到的在groovy中實現bean以外,我們還可以通過groovy提供的GroovyScriptEngine來執(zhí)行groovy腳本,這種方式不依賴于springframework,普通的java程序中也可以使用。

@Component
public class MyEngine {
    private final GroovyScriptEngine engine;

    @Autowired
    private FunBean funBean;

    public MyEngine() throws IOException {

        engine = new GroovyScriptEngine(ResourceUtils.getFile("classpath:scripts/").getAbsolutePath()
                , this.getClass().getClassLoader());
    }

    public void runScript(int x, int y) throws IllegalAccessException,
            InstantiationException, ResourceException, ScriptException {
        Class<GroovyObject> calcClass = engine.loadScriptByName("CalcScript.groovy");
        GroovyObject calc = calcClass.newInstance();

        Object result = calc.invokeMethod("calcSum", new Object[]{x, y});
        System.out.println("Result of CalcScript.calcSum() method is " + result);

        Binding binding = new Binding();
        binding.setVariable("arg", "test");
        binding.setVariable("funBean", funBean);
        Object result1 = engine.run("CalcScript.groovy", binding);
        System.out.println("Result of CalcScript.groovy is " + result1);
    }
}

首先我們初始化GroovyScriptEngine,在構造方法中傳入腳本文件的路徑。

執(zhí)行腳本的方法有2種,一種是獲取到GroovyObject,通過invokeMethod來執(zhí)行腳本中的某個方法,方法的參數通過Object數組傳入。

Class<GroovyObject> calcClass = engine.loadScriptByName("CalcScript.groovy");
GroovyObject calc = calcClass.newInstance();

Object result = calc.invokeMethod("calcSum", new Object[]{x, y});

第二種是直接運行groovy腳本,可以通過Binding將變量傳遞到groovy腳本中。

Binding binding = new Binding();
binding.setVariable("arg", "test");
binding.setVariable("funBean", funBean);
Object result1 = engine.run("CalcScript.groovy", binding);

感謝各位的閱讀,以上就是“springboot怎么集成groovy腳本使用”的內容了,經過本文的學習后,相信大家對springboot怎么集成groovy腳本使用這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI