Spring中集成Groovy的四种方式

groovy是一种动态脚本语言,适用于一些可变、和规则配置性的需求,目前Spring提供ScriptSource接口,支持两种类型,一种是

ResourceScriptSource,另一种是 StaticScriptSource,但是有的场景我们需要把groovy代码放进DB中,所以我们需要扩展这个。

Spring中集成Groovy的四种方式_第1张图片

ResourceScriptSource:在 resources 下面写groovy类

StaticScriptSource:把groovy类代码放进XML里

DatabaseScriptSource:把groovy类代码放进数据库中

工程模块为:

Spring中集成Groovy的四种方式_第2张图片

ResourceScriptSource

groovy的pom

1

2

3

4

5

6

<dependency>

    <artifactId>groovy-allartifactId>

    <groupId>org.codehaus.groovygroupId>

    <version>2.1.9version>

    <scope>compilescope>

  dependency>

HelloService接口

1

2

3

4

5

6

7

8

9

10

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实现类

Spring中集成Groovy的四种方式_第3张图片

1

2

3

4

5

6

7

8

9

10

11

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中配置

1

2

3

4

5

6

7

8

9

10

11

12

13

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

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);

  }

}

启动并测试 

Spring中集成Groovy的四种方式_第4张图片

StaticScriptSource

groovy的pom

1

2

3

4

5

6

<dependency>

     <artifactId>groovy-allartifactId>

     <groupId>org.codehaus.groovygroupId>

     <version>2.1.9version>

     <scope>compilescope>

   dependency>

HelloService接口

1

2

3

4

5

6

7

8

9

10

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中配置具体的实现类

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

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);

  }

}

启动并测试 

Spring中集成Groovy的四种方式_第5张图片

DatabaseScriptSource

下面我们先建表,把基本工作做完,这里我使用mybatisplus,dao、service等代码省略

1

2

3

4

5

6

7

8

9

10

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';

1

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、反射调用脚本的方法

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

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()

        .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");

  }

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

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 getBean(Class clazz) {

    return context.getBean(clazz);

  }

  public static T getBean(String name) {

    return (T) context.getBean(name);

  }

}

启动测试结果为:

Spring中集成Groovy的四种方式_第6张图片

总结:

优点:实时读取DB里的脚本,当脚本更改时,可以直接修改DB,对代码无侵入

缺点:每次都要查询DB,反射调用代码写死了

方法二:

1、我们模仿groovy-resource的思路,resource的XML配置是下面这样的

1

<lang:groovy id="helloService" script-source="classpath:groovy/HelloServiceImpl.groovy" />

所以,我们可以把DatabaseScriptSource的XML保存成这种格式

1

<lang:groovy id="helloService" script-source="database:helloService"/>

2、然后模仿Spring保存成XML格式的document的思路,我们也把groovy保存成XML格式的document,放进内存里

3、groovy的关键处理类是ScriptFactoryPostProcessor,当 Spring 装载应用程序上下文时,它首先创建工厂 bean(例如 GroovyScriptFactory bean)。然后,执行ScriptFactoryPostProcessor bean,用实际的脚本对象替换所有的工厂 bean。例如,我们本次测试的配置产生一个名为 helloService 的 bean,它的类型是groovierspring.GroovyHelloService。(如果启用 Spring 中的 debug 级日志记录,并观察应用程序上下文的启动,将会看到 Spring 首先创建一个名为 scriptFactory.helloService 的工厂 bean,然后 ScriptFactoryPostProcessor 从该工厂 bean 创建 helloService bean)。

你可能感兴趣的:(Spring中集成Groovy的四种方式)