Groovy — это динамический и объектно-ориентированный язык программирования, работающий на JVM. Он использует синтаксис, такой как Java, может быть встроен в Java и скомпилирован в байт-код. Java-код может быть вызван из Groovy, и наоборот. Некоторые из возможностей Groovy — это мета-функциональное программирование, динамическая типизация (с ключевым словом def), замыкания, GroovyBeans, Groovlets, интеграция с Bean Scripting Framework (BSF), обобщение, поддержка аннотаций и сборов.
В этой статье объясняется фундаментальная поддержка Spring Dynamic Language для Groovy следующими способами:
- Используя синтаксис Java и Spring Stereotype,
- Используя синтаксис Groovy и Spring Stereotype,
- Используя функцию встроенного скрипта ,
- С помощью поддержки языка Spring Groovy (lang: groovy) .
Используемые технологии:
- JDK 1.7.0_09
- Весна 3.2.0
- Groovy 2.0.4
- Maven 3.0.4
ШАГ 1: СОЗДАТЬ MAVEN ПРОЕКТ
Maven проект создается как показано ниже. (Его можно создать с помощью Maven или IDE Plug-in).
ШАГ 2: БИБЛИОТЕКИ
Во-первых, зависимости добавляются в pom.xml Maven.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
< 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 Plugin) используется для компиляции проекта с JDK 1.7
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
|
< 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
01
02
03
04
05
06
07
08
09
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
|
< 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: СОЗДАЙТЕ КЛАСС Сотрудника
Боб сотрудника создан.
01
02
03
04
05
06
07
08
09
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
|
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 Cache.
01
02
03
04
05
06
07
08
09
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.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 .
01
02
03
04
05
06
07
08
09
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
|
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.
01
02
03
04
05
06
07
08
09
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.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 .
01
02
03
04
05
06
07
08
09
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
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 , создан.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
|
xsi:schemaLocation='http://www.springframework.org/schema/beans < context:component-scan base-package = 'com.onlinetechvision.spring.srv, com.onlinetechvision.groovy.srv' /> </ beans > |
ШАГ 9: СОЗДАЙТЕ КЛАСС ПРИЛОЖЕНИЙ
Класс приложения создан для запуска приложения.
01
02
03
04
05
06
07
08
09
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
|
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 выходные журналы отображаются следующим образом:
1
2
3
4
5
6
7
|
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 SYNTAX
Интерфейс IGroovyEmployeeCacheService и GroovyEmployeeCacheService Impl также могут быть разработаны с использованием синтаксиса Groovy следующим образом:
ШАГ 12.1: СОЗДАНИЕ ИНТЕРФЕЙСА IGroovyEmployeeCacheService
Интерфейс IGroovyEmployeeCacheService создается с использованием синтаксиса Groovy.
01
02
03
04
05
06
07
08
09
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.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.
01
02
03
04
05
06
07
08
09
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
|
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: ИСПОЛЬЗОВАНИЕ ФУНКЦИИ INLINE-SCRIPT
GroovyEmployeeCacheService Impl также может быть определен с помощью функции встроенного скрипта следующим образом:
ШАГ 13.1: ОПРЕДЕЛИТЬ GroovyEmployeeCacheService IMPL через applicationContext.xml
Класс Impov GroovyEmployeeCacheService может быть определен в applicationContext.xml .
01
02
03
04
05
06
07
08
09
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
xsi:schemaLocation='http://www.springframework.org/schema/beans < 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: ИСПОЛЬЗОВАНИЕ ПОДДЕРЖКИ ЯЗЫКОВ ВЕСНЫ
GroovyEmployeeCacheService Impl также может быть определен для контекста приложения Spring без использования стереотипа (@Service) следующим образом:
ШАГ 14.1: ОПРЕДЕЛИТЬ GroovyEmployeeCacheService IMPL через applicationContext.xml
Класс Impov GroovyEmployeeCacheService может быть определен в applicationContext.xml.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
|
xsi:schemaLocation='http://www.springframework.org/schema/beans < 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
РЕСУРСЫ :
Groovy Руководство пользователя
Поддержка Spring Dynamic Language
Ссылка: Spring Dynamic Language Support с Groovy от нашего партнера по JCG Эрен Авсарогуллари в блоге Online Technology Vision .