Groovy是一种在JVM上运行的动态且面向对象的编程语言。 它使用Java之类的语法,可以嵌入Java并编译为字节码。 可以从Groovy调用Java代码,反之亦然。 Groovy的一些功能包括元和函数编程,动态类型化(使用def关键字),闭包,GroovyBeans,Groovlets,与Bean脚本框架(BSF)集成,泛型,注释和集合支持。
本文通过以下方式介绍了对Groovy的基本Spring Dynamic Language支持:
- 通过使用Java语法和Spring 构造型,
- 通过使用Groovy语法和Spring 构造型,
- 通过使用内联脚本功能 ,
- 通过使用Spring Groovy语言支持(lang:groovy) 。
二手技术:
- JDK 1.7.0_09
- Spring3.2.0
- Groovy 2.0.4
- Maven的3.0.4
步骤1:建立已完成的专案
创建一个Maven项目,如下所示。 (可以使用Maven或IDE插件来创建它)。
步骤2:图书馆
首先,将依赖项添加到Maven的pom.xml中。
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>3.2.0.RELEASE</spring.version>
</properties>
<!-- Spring 3 dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>2.0.4</version>
</dependency>
maven-compiler-plugin(Maven插件)用于使用JDK 1.7编译项目
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<compilerId>groovy-eclipse-compiler</compilerId>
<verbose>true</verbose>
<source>1.7</source>
<target>1.7</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
<dependencies>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-eclipse-compiler</artifactId>
<version>2.6.0-01</version>
</dependency>
</dependencies>
</plugin>
maven-shade-plugin(Maven插件)可用于创建runnable-jar
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.0</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
<transformers>
<transformer
implementation='org.apache.maven.plugins.shade.resource.ManifestResourceTransformer'>
<mainClass>com.onlinetechvision.exe.Application</mainClass>
</transformer>
<transformer
implementation='org.apache.maven.plugins.shade.resource.AppendingTransformer'>
<resource>META-INF/spring.handlers</resource>
</transformer>
<transformer
implementation='org.apache.maven.plugins.shade.resource.AppendingTransformer'>
<resource>META-INF/spring.schemas</resource>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
步骤3:建立员工班级
员工 Bean已创建。
package com.onlinetechvision.employee;
/**
* Employee Bean
*
* @author onlinetechvision.com
* @since 24 Dec 2012
* @version 1.0.0
*
*/
public class Employee {
private String id;
private String name;
private String surname;
public Employee(String id, String name, String surname) {
this.id = id;
this.name = name;
this.surname = surname;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((surname == null) ? 0 : surname.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (surname == null) {
if (other.surname != null)
return false;
} else if (!surname.equals(other.surname))
return false;
return true;
}
@Override
public String toString() {
return 'Employee [id=' + id
+ ', name=' + name
+ ', surname=' + surname + ']';
}
}
方法1:使用JAVA SYNTAX
步骤4:建立IGroovyEmployeeCacheService接口
创建IGroovyEmployeeCacheService接口以公开Groovy缓存功能。
package com.onlinetechvision.groovy.srv
import com.onlinetechvision.employee.Employee
/**
* IGroovyEmployeeCacheService Interface exposes cache functionality.
*
* @author onlinetechvision.com
* @since 24 Dec 2012
* @version 1.0.0
*
*/
interface IGroovyEmployeeCacheService {
/**
* Adds employee entry to cache
*
* @param Employee employee
*
*/
void addToEmployeeCache(Employee employee);
/**
* Gets employee entry from cache
*
* @param String id
* @return Employee employee
*/
Employee getFromEmployeeCache(String id);
/**
* Removes employee entry from cache
*
* @param Employee employee
*
*/
void removeFromEmployeeCache(Employee employee);
}
步骤5:创建GroovyEmployeeCacheService IMPL
GroovyEmployeeCacheService类是通过实现IGroovyEmployeeCacheService接口创建的。
package com.onlinetechvision.groovy.srv
import com.onlinetechvision.employee.Employee;
import org.springframework.stereotype.Service;
/**
* GroovyEmployeeCacheService Class is implementation of IGroovyEmployeeCacheService Interface.
*
* @author onlinetechvision.com
* @since 24 Dec 2012
* @version 1.0.0
*
*/
@Service
class GroovyEmployeeCacheService implements IGroovyEmployeeCacheService {
private Map<String, Employee> cache = new HashMap();
/**
* Adds employee entry to cache
*
* @param Employee employee
*
*/
public void addToEmployeeCache(Employee employee) {
getCache().put(employee.getId(), employee);
println print(employee, 'added to cache...');
}
/**
* Gets employee entry from cache
*
* @param String id
* @return Employee employee
*/
public Employee getFromEmployeeCache(String id) {
Employee employee = getCache().get(id);
println print(employee, 'gotten from cache...');
return employee;
}
/**
* Removes employee entry from cache
*
* @param Employee employee
*
*/
public void removeFromEmployeeCache(Employee employee) {
getCache().remove(employee.getId());
println print(employee, 'removed from cache...');
println 'Groovy Cache Entries :' + getCache();
}
public Map<String, Employee> getCache() {
return cache;
}
public void setCache(Map<String, Employee> map) {
cache = map;
}
/**
* Prints operation information
*
* @param Employee employee
* @param String description
*
*/
private String print(Employee employee, String desc) {
StringBuilder strBldr = new StringBuilder();
strBldr.append(employee)
strBldr.append(' ');
strBldr.append(desc);
return strBldr.toString();
}
}
步骤6:建立IEmployeeService接口
IUserService接口是为Spring服务层创建的,显示了如何集成Spring和Groovy服务层。
package com.onlinetechvision.spring.srv;
import com.onlinetechvision.employee.Employee;
/**
* IEmployeeService Interface is created to represent Spring Service layer.
*
* @author onlinetechvision.com
* @since 24 Dec 2012
* @version 1.0.0
*
*/
public interface IEmployeeService {
/**
* Adds Employee entry to cache
*
* @param Employee employee
*
*/
void addToGroovyEmployeeCache(Employee employee);
/**
* Gets Employee entry from cache
*
* @param String id
* @return Employee employee
*/
Employee getFromGroovyEmployeeCache(String id);
/**
* Removes Employee entry from cache
*
* @param Employee employee
*
*/
void removeFromGroovyEmployeeCache(Employee employee);
}
步骤7:创建EmployeeService IMPL
EmployeeService类是通过实现IUserService接口创建的。
package com.onlinetechvision.spring.srv;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.onlinetechvision.employee.Employee;
import com.onlinetechvision.groovy.srv.IGroovyEmployeeCacheService;
/**
* EmployeeService Class is implementation of IEmployeeService interface.
*
* @author onlinetechvision.com
* @since 24 Dec 2012
* @version 1.0.0
*
*/
@Service
public class EmployeeService implements IEmployeeService {
@Autowired
private IGroovyEmployeeCacheService groovyEmployeeCacheService ;
/**
* Adds Employee entry to cache
*
* @param Employee employee
*
*/
public void addToGroovyEmployeeCache(Employee employee) {
getGroovyEmployeeCacheService().addToEmployeeCache(employee);
}
/**
* Gets Employee entry from cache
*
* @param String id
* @return Employee employee
*/
public Employee getFromGroovyEmployeeCache(String id) {
return getGroovyEmployeeCacheService().getFromEmployeeCache(id);
}
/**
* Removes Employee entry from cache
*
* @param Employee employee
*
*/
public void removeFromGroovyEmployeeCache(Employee employee) {
getGroovyEmployeeCacheService().removeFromEmployeeCache(employee);
}
public IGroovyEmployeeCacheService getGroovyEmployeeCacheService() {
return groovyEmployeeCacheService;
}
public void setGroovyEmployeeCacheService(IGroovyEmployeeCacheService groovyEmployeeCacheService) {
this.groovyEmployeeCacheService = groovyEmployeeCacheService;
}
}
步骤8:创建applicationContext.xml
Spring配置文件applicationContext.xml已创建。
<beans xmlns='http://www.springframework.org/schema/beans'
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xmlns:context='http://www.springframework.org/schema/context'
xsi:schemaLocation='http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd'>
<context:component-scan base-package='com.onlinetechvision.spring.srv, com.onlinetechvision.groovy.srv'/>
</beans>
步骤9:创建应用程序类
创建应用程序类以运行应用程序。
package com.onlinetechvision.exe;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.onlinetechvision.spring.srv.EmployeeService;
import com.onlinetechvision.spring.srv.IEmployeeService;
import com.onlinetechvision.employee.Employee;
/**
* Application Class starts the application
*
* @author onlinetechvision.com
* @since 24 Dec 2012
* @version 1.0.0
*
*/
public class Application
{
/**
* Starts the application
*
* @param String[] args
*
*/
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext('applicationContext.xml');
IEmployeeService employeeService = (IEmployeeService) context.getBean(EmployeeService.class);
Employee firstEmployee = new Employee('1', 'Jake', 'Gyllenhaal');
Employee secondEmployee = new Employee('2', 'Woody', 'Harrelson');
employeeService.addToGroovyEmployeeCache(firstEmployee);
employeeService.getFromGroovyEmployeeCache(firstEmployee.getId());
employeeService.removeFromGroovyEmployeeCache(firstEmployee);
employeeService.addToGroovyEmployeeCache(secondEmployee);
employeeService.getFromGroovyEmployeeCache(secondEmployee.getId());
}
}
步骤10:建立专案
生成OTV_Spring_Groovy项目后,将创建OTV_Spring_Groovy-0.0.1-SNAPSHOT.jar 。
步骤11:运行项目
运行创建的OTV_Spring_Groovy-0.0.1-SNAPSHOT.jar文件后,输出日志显示为followingwing:
Employee [id=1, name=Jake, surname=Gyllenhaal] added to cache...
Employee [id=1, name=Jake, surname=Gyllenhaal] gotten from cache...
Employee [id=1, name=Jake, surname=Gyllenhaal] removed from cache...
Groovy Cache Entries :[:]
Employee [id=2, name=Woody, surname=Harrelson] added to cache...
Employee [id=2, name=Woody, surname=Harrelson] gotten from cache...
到目前为止,已经解释了第一种方法。 让我们看看其他方式:
方法2:使用Groovy语法
IGroovyEmployeeCacheService接口和GroovyEmployeeCacheService Impl也可以使用Groovy语法进行如下设计:
步骤12.1:创建IGroovyEmployeeCacheService接口
IGroovyEmployeeCacheService接口是使用Groovy语法创建的。
package com.onlinetechvision.groovy.srv
import com.onlinetechvision.employee.Employee
/**
* IGroovyEmployeeCacheService Interface exposes cache functionality.
*
* @author onlinetechvision.com
* @since 24 Dec 2012
* @version 1.0.0
*
*/
interface IGroovyEmployeeCacheService {
/**
* Adds employee entry to cache
*
* @param Employee employee
*
*/
def addToEmployeeCache(Employee employee);
/**
* Gets employee entry from cache
*
* @param String id
* @return Employee employee
*/
def getFromEmployeeCache(String id);
/**
* Removes employee entry from cache
*
* @param Employee employee
*
*/
def removeFromEmployeeCache(Employee employee);
}
步骤12.2:创建GroovyEmployeeCacheService IMPL
GroovyEmployeeCacheService类是使用Groovy语法创建的。
package com.onlinetechvision.groovy.srv
import com.onlinetechvision.employee.Employee;
import org.springframework.stereotype.Service;
/**
* GroovyEmployeeCacheService Class is implementation of IGroovyEmployeeCacheService Interface.
*
* @author onlinetechvision.com
* @since 24 Dec 2012
* @version 1.0.0
*
*/
@Service
class GroovyEmployeeCacheService implements IGroovyEmployeeCacheService {
def cache = new HashMap();
/**
* Adds employee entry to cache
*
* @param Employee employee
*
*/
def addToEmployeeCache(Employee employee) {
getCache().put(employee.getId(), employee);
println print(employee, 'added to cache...');
}
/**
* Gets employee entry from cache
*
* @param String id
* @return Employee employee
*/
def getFromEmployeeCache(String id) {
Employee employee = getCache().get(id);
println print(employee, 'gotten from cache...');
return employee;
}
/**
* Removes employee entry from cache
*
* @param Employee employee
*
*/
def removeFromEmployeeCache(Employee employee) {
getCache().remove(employee.getId());
println print(employee, 'removed from cache...');
println 'Groovy Cache Entries :' + getCache();
}
def getCache() {
return cache;
}
def setCache(Map<String, Employee> map) {
cache = map;
}
/**
* Prints operation information
*
* @param Employee employee
* @param String description
*
*/
def print(Employee employee, String desc) {
StringBuilder strBldr = new StringBuilder();
strBldr.append(employee)
strBldr.append(' ');
strBldr.append(desc);
}
}
方法3:使用内联脚本功能
GroovyEmployeeCacheService Impl也可以通过使用以下内联脚本功能进行定义:
步骤13.1:通过applicationContext.xml定义GroovyEmployeeCacheService IMPL
GroovyEmployeeCacheService Impl类可以在applicationContext.xml中定义。
<beans xmlns='http://www.springframework.org/schema/beans'
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xmlns:context='http://www.springframework.org/schema/context'
xmlns:lang='http://www.springframework.org/schema/lang'
xsi:schemaLocation='http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/lang
http://www.springframework.org/schema/lang/spring-lang-3.0.xsd'>
<context:component-scan base-package='com.onlinetechvision.spring.srv'/>
<lang:groovy id='groovyEmployeeCacheService'>
<lang:inline-script>
package com.onlinetechvision.groovy.srv
import com.onlinetechvision.employee.Employee;
import org.springframework.stereotype.Service;
class GroovyEmployeeCacheService implements IGroovyEmployeeCacheService {
def cache = new HashMap();
def addToEmployeeCache(Employee employee) {
getCache().put(employee.getId(), employee);
println print(employee, 'added to cache...');
}
def getFromEmployeeCache(String id) {
Employee employee = getCache().get(id);
println print(employee, 'gotten from cache...');
return employee;
}
def removeFromEmployeeCache(Employee employee) {
getCache().remove(employee.getId());
println print(employee, 'removed from cache...');
println 'Groovy Cache Entities :' + getCache();
}
def getCache() {
return cache;
}
def setCache(Map map) {
cache = map;
}
def print(Employee employee, String desc) {
StringBuilder strBldr = new StringBuilder();
strBldr.append(employee)
strBldr.append(' ');
strBldr.append(desc);
}
}
</lang:inline-script>
</lang:groovy>
</beans>
方法4:使用Spring Groovy语言支持
还可以将GroovyEmployeeCacheService Impl定义为Spring应用程序上下文,而无需使用以下构造型(@Service):
步骤14.1:通过applicationContext.xml定义GroovyEmployeeCacheService IMPL
GroovyEmployeeCacheService Impl类可以在applicationContext.xml中定义。
<beans xmlns='http://www.springframework.org/schema/beans'
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xmlns:context='http://www.springframework.org/schema/context'
xmlns:lang='http://www.springframework.org/schema/lang'
xsi:schemaLocation='http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/lang
http://www.springframework.org/schema/lang/spring-lang-3.0.xsd'>
<context:component-scan base-package='com.onlinetechvision.spring.srv'/>
<lang:groovy id='groovyEmployeeCacheService' script-source='classpath:com/onlinetechvision/groovy/srv/GroovyEmployeeCacheService.groovy'/>
</beans>
步骤15:下载
https://github.com/erenavsarogullari/OTV_Spring_Groovy
资源:
参考: Online Technology Vision博客上来自我们JCG合作伙伴 Eren Avsarogullari的Groovy提供的Spring动态语言支持 。
翻译自: https://www.javacodegeeks.com/2013/01/spring-dynamic-language-support-with-groovy.html