У меня есть Java-приложение с начальной загрузкой 2, и я хотел бы использовать интерпретированный (не скомпилированный) Groovy-код для внедрения aop. Из чтения весенней документации это звучит так, как будто это возможно, но я не смог найти никаких примеров.
AOP - консультирование скриптовых компонентов :
Вы, конечно, не ограничены только советами bean-компонентов со сценариями ... вы также можете сами писать аспекты на поддерживаемом динамическом языке и использовать такие bean-компоненты для консультирования других bean-компонентов Spring. Это действительно было бы расширенное использование поддержки динамического языка.
В конце я хотел бы иметь каталог, в который я мог бы добавить groovy-скрипты (для бизнес-логики) в приложение, которое внедрит себя через spring-aop.
Что я не уверен в том, что весенняя загрузка 2 автоматически делает в таком случае, или я должен интегрировать код, основанный на org.springframework.scripting вручную?
Итак, вот мой маленький тестовый проект:
project
|-pom.xml
|src/main/java/de/test
|-Commandline.java
|-MytestApplication.java
|-TestConfig.java
|-GetText.java
|src/main/resources/groovy
|-testAspect.groovy
|src/main/resources
|-application.properties (empty at the moment)
|-applicationContext.xml
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>de.test</groupId>
<artifactId>mytest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>mytest</name>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath/>
</parent>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy</artifactId>
</dependency>
</dependencies>
</project>
TestConfig.java
package de.test;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configuration
@EnableAspectJAutoProxy
@ComponentScan({"de.test", "groovy"})
@ImportResource({"classpath*:applicationContext.xml"})
public class TestConfig
{
}
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:lang="http://www.springframework.org/schema/lang" xmlns:aop="http://www.springframework.org/schema/aop" 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 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<lang:groovy id="testAspect" refresh-check-delay="30000" script-source="classpath:groovy/TestAspect.groovy"/>
</beans>
MytestApplication.java
package de.test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan({"de.test", "groovy"})
@SpringBootApplication
public class SpringboottestApplication
{
public static void main(final String[] args)
{
SpringApplication.run(SpringboottestApplication.class, args);
}
}
GetText.java
package de.test;
import org.springframework.stereotype.Component;
@Component
public class GetText
{
public String getText()
{
return "test1";
}
}
Commandline.java
package de.test;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class Commandline implements CommandLineRunner
{
@Autowired
GetText textbean;
public Commandline()
{
super();
}
@Override
public void run(final String... args) throws Exception
{
System.out.println((this.textbean.getText());
}
}
testAspect.groovy
package groovy
import org.springframework.stereotype.Component
import org.aspectj.lang.ProceedingJoinPoint
import org.aspectj.lang.annotation.Around
import org.aspectj.lang.annotation.Aspect
@Aspect
@Component
class TestAspect
{
@Around("execution(String de.test.GetText.getText())")
public String doChangeGetText(ProceedingJoinPoint pjp) throws Throwable
{
String retVal = (String)pjp.proceed();
return retVal + "; test2";
}
}
После
mvn clean install
Я начинаю с
java -jar target/mytest-0.0.1-SNAPSHOT.jar
Что приводит к выводу только "test1" вместо требуемого "test1; test2".
Update1:
- Добавлен TestConfig.java
- Перемещено src / main / groovy / groovy / testAspect.groovy в src / main / resources / groovy / testAspect.groovy
- Улучшены некоторые вещи, но все равно не работает.
Update2:
- Добавлен GetText.java
- Изменен Commandline.java для использования bean-компонента GetText
- Изменен PointCut
- Все еще не работает
Update3:
- Добавлено applicationContext.xml
- Теперь выполняется в org.springframework.aop.AopInvocationException: несоответствие аргументов методу совета [public java.lang.String groovy.TestAspect.doChangeGetText (org.aspectj.lang.ProceedingJoinPoint) бросает java.lang.Throwable выражение pointcut [org.aspectj.weaver.internal.tools.PointcutExpressionImpl@4c4f4365]; Вложенным исключением является java.lang.IllegalArgumentException: объект не является экземпляром объявления класса
- При копировании testAspect.groovy в качестве java-класса - тогда pointcut работает как положено, и к нему добавляется «; test 2», но как сценарий groovy вышеприведенное исключение будет иметь место.
- Добавление интерфейса IGetText и / или IAspectTest не поможет