java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Springboot groovy

Springboot中动态语言groovy介绍

作者:Chuang-2

Apache的Groovy是Java平台上设计的面向对象编程语言,这门动态语言拥有类似Python、Ruby和Smalltalk中的一些特性,可以作为Java平台的脚本语言使用,这篇文章主要介绍了springboot中如何使用groovy,需要的朋友可以参考下

Groovy

Groovy是一种基于Java的语法的基于JVM的编程语言。Groovy支持动态输入,闭包,元编程,运算符重载等等语法。除此之外,Groovy还提供了许多类似脚本语言的功能,比如,多行字符串,字符串插值,优雅的循环结构和简单的属性访问。另外,结尾分号是可选的。而这些都有足够的理帮助开发人员为了提高开发效率。

换句话说,Groovy就是一种继承了动态语言的优良特性并运行在JVM上的编程语言。由于Groovy的语法非常接近Java,所以Java开发人员很容易开始使用Groovy。 Spring Boot应用中也支持使用Groovy编程语言进行开发。

pom

<!-- groovy -->
<dependency>
    <artifactId>groovy</artifactId>
    <groupId>org.codehaus.groovy</groupId>
    <version>2.5.8</version>
    <scope>compile</scope>
</dependency>

ResourceScriptSource

@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        ConfigurableApplicationContext run = SpringApplication.run(DemoApplication.class, args);
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-groovy.xml");
        GroovyService bean = context.getBean(GroovyService.class);
        String sayHello = bean.sayHello();
        System.out.println(sayHello);
    }
}
public interface GroovyService {
    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.example.demo.groovy.GroovyService
            class HelloServiceImpl implements GroovyService {
                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>

DatabaseScriptSource

方法一:

实时读取DB里的groovy脚本文件

利用GroovyClassLoader去编译脚本文件

把class对象注入成Spring bean

反射调用脚本的方法

CREATE TABLE `groovy_script` (
  `id` bigint 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=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='groovy script';
INSERT INTO book_shop2.groovy_script
(id, script_name, script_content, status, extend_info, created_time, modified_time)
VALUES(1, 'groovyService', 'import com.example.demo.groovy.GroovyService
            class HelloServiceImpl implements GroovyService {
				@Override
				String sayHello() {
					return "sayHello";
				}
                @Override
                String sayHello(String name) {
                    return "Hello " + name + ". Welcome to static script in Groovy.";
                }
            }', 'ENABLE', NULL, '2020-09-26 17:16:36.477818000', '2022-09-04 22:54:51.421959000');
@RestController
public class GroovyController {
    @Autowired
    GroovyScriptMapper groovyScriptMapper;
    @GetMapping("/aaaa")
    private String groovyTest() throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException {
        GroovyScript groovyScript = this.groovyScriptMapper.getOne(1L);
        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);
        String aaaaaaa = (String) method.invoke(o, "aaaaaaa");
        System.out.println(aaaaaaa);
        return aaaaaaa;
    }
}
/*
import com.example.demo.groovy.GroovyService
            class HelloServiceImpl implements GroovyService {
				@Override
				String sayHello() {
					return "sayHello";
				}
                @Override
                String sayHello(String name) {
                    return "Hello " + name + ". Welcome to static script in Groovy.";
                }
            }
Hello aaaaaaa. Welcome to static script in Groovy.
*/
public interface GroovyScriptMapper extends BaseMapper<GroovyScript> {
    @Select({"select script_content from groovy_script where id = #{id}"})
    @Result(column = "script_content", property = "scriptContent")
    GroovyScript getOne(Long id);
}
@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);
    }
}

到此这篇关于Springboot中动态语言groovy介绍的文章就介绍到这了,更多相关Springboot groovy内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文