栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring中集成Groovy的四种方式(小结)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring中集成Groovy的四种方式(小结)

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

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

ResourcescriptSource:在 resources 下面写groovy类

StaticscriptSource:把groovy类代码放进XML里

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

工程模块为:

ResourcescriptSource

groovy的pom

  
      groovy-all
      org.codehaus.groovy
      2.1.9
      compile
    

HelloService接口

package com.maple.resource.groovy;


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




  
    
  

主类 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

 
      groovy-all
      org.codehaus.groovy
      2.1.9
      compile
    

HelloService接口

package com.maple.groovy.staticscript.groovy;


public interface HelloService {

  String sayHello();
}

在spring-groovy.xml中配置具体的实现类




  

    

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

    

    

  

主类 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.groovyrnrnimport com.maple.database.groovy.HelloServicernrnpublic class HelloServiceImpl implements HelloService {rnrn  @Overridern  String sayHello(String name) {rn    return "Hello "+name+". Welcome to database in Groovy.";rn  }rn}', '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;


@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");
  }
}
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;


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

  }
}

启动测试结果为:

总结:

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

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

方法二:

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

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

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

我们发现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;


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


public final class DatabasescriptSource implements scriptSource {

  
  private String 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中 

这样的话,我们就能从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;


@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;
  }
}

 总结:

优点:项目初始化的时候,就把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;


@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 groovyscripts = groovyscriptService.list(new QueryWrapper().eq("status", "ENABLE"));

    List 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 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内容请搜索考高分网以前的文章或继续浏览下面的相关文章希望大家以后多多支持考高分网!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/131351.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号