`
yangzb
  • 浏览: 3493833 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Spring’s so Groovy

    博客分类:
  • Java
阅读更多

 

Spring 2.0 introduced comprehensive support to use dynamic languages. It supports three different scripting languages; JRuby , Groovy and BeanShell . The scripting language used in this article is Groovy; which I think was designed for Java developers. As Scott Davis says in his book, Groovy Recipes ” Groovy is Java at the end of the day”. “Spring Recipes - A Problem -Solution Approach ” written by Gary Mak has a complete chapter dedicated to Scripting in Spring . The author covers all the three dynamic languages supported by Spring; JRuby , Groovy and BeanShell .

There are times when in your application you have certain modules that require frequent changes, and based on these changes you need to change the business logic within your modules. If these modules were written in Java, you can imagine what needs to be done at this point; recompile, package, redeploy. This is where modules written in these dynamic languages come in handy, there is no need to recompile, or redeploy for these changes to take effect. In most cases, you want the Spring container to be able to detect these changes and also pick up the new state from the changed script source. Spring allows you to do this as well by setting one simple attribute.

Hello World Example: It is customary to start any tutorial by writing a simple HelloWorld program, right? We are going to use Groovy in this tutorial. This tutorial assumes you have some knowledge of Spring and Groovy. I used Eclipse IDE for this tutorial, and to work with Spring and Groovy in Eclipse, you need the following libraries in your build path.

java-build-path

So, lets begin with the HelloWorld example here.

Step 1: Lets define an interface for our HelloWorld Service :

package com.springandgroovy;

public interface HelloWorldService {

	String sayHello();

}

Step 2 : Implement the interface in Groovy.
Next, we implement this interface in Groovy by creating a simple script within the com.springandgroovy package as such:

import com.springandgroovy.HelloWorldService;

class HelloWorldServiceImpl implements HelloWorldService {

	String name

   String sayHello()
   {
   		"Hello $name. Welcome to Scripting in Groovy."
   }
}

Step 3: Make changes to Spring’s configuration file.
Here comes the Spring’s bean configuration file, in which you have to include the lang schema to use the custom dynamic language tags.

<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-2.5.xsd
        http://www.springframework.org/schema/lang
        http://www.springframework.org/schema/lang/spring-lang-2.5.xsd">

the bean definition for the Groovy backed HelloWorldService looks like this:

<lang:groovy id="helloWorldService"
			 script-source="classpath:com/springandgroovy/HelloWorldServiceImpl.groovy">
			 <lang:property name="name" value="meera"/>
</lang:groovy>

That’s all you need to use Groovy backed beans in Spring. So, how do we know this works, right? Lets write a simple Main class and test it within our IDE:

Step 4: Run the HelloWorldService.

package com.springandgroovy;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

   public static void main(String[] args) throws Exception {

     ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
     HelloWorldService service = (HelloWorldService) context.getBean("helloWorldService");

     System.out.println(service.sayHello());

    }

}

And you should be able to see output in the console as such:

console-window

Step 5: Refreshable Beans.
As I mentioned earlier also, to turn on this feature we have to specify one simple attribute refresh-check-delay on the element of our bean definition as such:

<lang:groovy id="helloWorldService"
			 script-source="classpath:com/springandgroovy/HelloWorldServiceImpl.groovy"
			 refresh-check-delay="5000">
			 <lang:property name="name" value="meera"/>
</lang:groovy>

Again, how do we know this works when we make changes to our Groovy Script? A small change in our Main class and, and you should be set to test that this works as well:

package com.springandgroovy;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

    public static void main(String[] args) throws Exception {

    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    HelloWorldService service = (HelloWorldService) context.getBean("helloWorldService");
    System.in.read();
    System.out.println(service.sayHello());

    }

}

Now, run the Main class in your IDE, it halts because of the System.in.read line, make a few changes within your script, save it, hit enter in your console window in your IDE. The Spring container read our new changes and prints the results within the console window.

The script change can be as simple as adding a few special characters as such within the sayHello() method:

   String sayHello()
   {
   		"Hello $name!!!. Welcome to Scripting in Groovy."
   }

And the console window reflects these changes:

updated-console-window

Step 6: Inline Scripts
Spring also allows you to embed scripts directly within the Spring bean definitions inside your Spring configuration file. I am no fan of doing this, because it has a drawback; the refresh attribute is not applicable for inline scripts. Lets take a look at this in case you need to use this feature:

Copy the script we wrote in Step 2 and paste it within the lang:inline-script element as such:

   <lang:groovy id="helloWorldService">
        <lang:inline-script>
        <![CDATA[
 import com.springandgroovy.HelloWorldService;
  class HelloWorldServiceImpl implements HelloWorldService {

	String name

   String sayHello()
   {
   		"Hello $name. Welcome to Scripting in Groovy"
   }
}
        ]]>
        </lang:inline-script>
        <lang:property name="name" value="meera" />
    </lang:groovy>


Run the Main class and you should see the same output in your console window.

console-window

In this tutorial we learned how to use Groovy with Spring using an external script source file, how to refresh changes when a script source file is changed, and finally saw an inline script which was embedded within the Spring configuration file.

Additional Resources:

1. JRuby
2. Groovy
3. BeanShell
4. Spring
5. Spring Recipes

分享到:
评论

相关推荐

    microservices-spring-boot-groovy:使用 Spring Boot 和 Groovy 构建微服务

    微服务-spring-boot-groovy 使用 Spring Boot 和 Groovy 构建微服务创建这些项目是为了在当地的达拉斯 Groovy Grails 用户组会议上展示微服务架构这些服务使用您需要安装才能开始使用的各种外部服务。 您将需要安装 ...

    spring-beans-groovy源码

    《深入剖析Spring Beans与Groovy集成的源码》 在软件开发中,Spring框架以其强大的依赖注入和面向切面编程特性,成为了Java企业级应用的事实标准。而在动态语言的使用上,Groovy凭借其简洁的语法和对Java平台的无缝...

    Groovy在Spring中的简单使用

    Groovy 在 Spring 中的简单使用 Groovy 是一种敏捷的动态语言,用于 Java 虚拟机,可以与 Java 代码无缝集成。它的类 Java 语法对于 Java 开发人员来说很自然,且可以作为纯粹的脚本语言使用。在 Spring 中动态使用...

    groovy+maven+spring

    在IT行业中,构建高效、灵活的应用常常涉及到多种技术的整合,比如"groovy+maven+spring"这样的组合。这个组合提供了强大的动态脚本语言Groovy、项目管理工具Maven以及广泛应用的Spring框架的集成,使得开发过程更加...

    groovy+spring在web中的应用

    将Groovy与Spring结合,可以利用Groovy的简洁语法和动态特性来增强Spring应用的开发效率和可读性。 首先,Groovy在Spring中的应用主要体现在以下几个方面: 1. **配置文件简化**:Groovy的脚本特性使得我们可以用...

    groovy入门经典,groovyeclipse 插件

    Groovy是一种动态、灵活的编程语言,它是Java平台上的一个扩展,可以无缝集成到Java项目中。Groovy的语法简洁,支持面向对象编程、函数式编程,并提供了许多现代语言特性,如闭包和动态类型。这使得Groovy成为快速...

    spring-boot-groovy-config:使用Groovy文件配置Spring Boot应用程序

    spring-boot-groovy-config 使用Groovy文件配置Spring Boot应用程序。 这不仅允许以时髦的DSL方式指定属性,而且还允许(小的)逻辑并在配置内部重复使用(请注意,配置中的复杂逻辑通常不是一个好主意,但是在某些...

    Groovy学习资料

    Spring Boot与Groovy的结合也是常见的应用场景,Groovy的简洁语法使得配置Spring Bean变得简单易懂。 Groovy还广泛应用于持续集成工具Jenkins的脚本编写,通过Jenkinsfile来定义构建流程。此外,Spock是一个用于...

    Java中使用Groovy的三种方式

    Groovy的动态性使得编写Spring配置和Bean定义更加直观,而Spring Boot的"约定优于配置"理念与Groovy的简洁性相得益彰。 ```groovy @RestController class HelloWorldController { @GetMapping('/') String hello...

    orientdb-spring-boot-example:Spring Boot Ang Groovy的OrientDB使用示例

    orientdb-spring-boot-example 带有spring boot ang groovy和 lib的OrientDB用法示例在 lib提供的IntelliJ IDEA中突出显示了完整的方法。 ###您可以从该项目中学到什么使用OrientDB图形和文档本机api,但仍然保持...

    groovy

    2. Web开发:Grails框架基于Groovy,提供了一种快速构建Web应用的方式,与Spring Boot等Java框架相比,开发速度更快。 3. 数据处理:Groovy可以方便地处理XML、JSON等数据格式,常用于数据转换和解析。 4. 测试:...

    apache-groovy-3.0.8.zip apache官网的groovy3.0.8版本

    apache-groovy-3.0.8.zip apache官网的groovy3.0.8版本,希望大家多多下载,apache-groovy-3.0.8.zip apache官网的groovy3.0.8版本,希望大家多多下载,apache-groovy-3.0.8.zip apache官网的groovy3.0.8版本,希望...

    Groovy+Tapestry5+Spring2.5+Hibernate3.2实现CRUD

    标题 "Groovy+Tapestry5+Spring2.5+Hibernate3.2实现CRUD" 涉及到的是一个使用几种技术栈构建Web应用程序的示例。这个项目结合了Groovy、Tapestry 5、Spring 2.5和Hibernate 3.2,旨在展示如何在实际开发中进行数据...

    groovy-all-2.4.8.jar

    - Groovy可以无缝集成到Spring框架中,创建Spring Bean和配置文件。 - 与Java EE平台集成,如EJB、JMS、JPA等,提供了更简单的API和更灵活的编程模型。 - 与大数据技术结合,如Apache Kafka、Hadoop等,可以编写...

    Java调用Groovy,实时动态加载数据库groovy脚本

    1. 引入Groovy库:在Java项目中添加Groovy的相关依赖,通常是`groovy-all`,确保Java能够访问Groovy运行时环境。 2. 创建GroovyClassLoader:使用这个类加载器可以动态加载和执行Groovy脚本。它继承自Java的...

    groovy学习

    - Groovy可以与Spring框架无缝集成,创建Spring Beans时,Groovy类可以直接作为配置,无需XML。 - 使用`@GrailsCompileStatic`注解可以将Groovy类转换为静态类型的类,以获得更好的性能和类型安全。 - 在Spring ...

    groovy-2.3.6-installer

    Groovy是一种动态、开源的编程语言,它是Java平台上的一个JVM(Java Virtual Machine)语言。Groovy结合了Python、Ruby和Perl等脚本语言的简洁性和灵活性,并且完全兼容Java,可以无缝地与Java代码集成。在"groovy-...

    groovy-loader:在文件目录中动态加载Groovy脚本

    使用spring配置文件来管理注册groovy bean:每一个spring配置文件作为一个ApplicationContext,管理一个namespace下的groovy bean spring配置文件使用标签lang:groovy,通过指定script-source来加载指定路径下的...

Global site tag (gtag.js) - Google Analytics