Here is a solution using annotations, using AspectJ :
First, define the desired annotation:
package partition;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Partitioned {
/**
* The size of the partition, for instance 30000
*/
int size();
}
Thus your service will look like:
package partition;
import java.util.List;
public class AccountService {
private AccountRepository accountRepository;
public AccountService(AccountRepository accountRepository) {
this.accountRepository = accountRepository;
}
@Partitioned(size = 30000)
public List<Account> getAccounts(List<Long> ids) {
return accountRepository.getAccounts(ids);
}
}
So far it's easy. Then comes the processing of the annotation, where AspectJ enters the game. Define an aspect linked to the annotation:
package partition;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@Aspect
public class PartitionedAspect {
@Pointcut("@annotation(partitioned)")
public void callAt(Partitioned partitioned) {
}
@Around("callAt(partitioned)")
public <T, D> Object around(ProceedingJoinPoint pjp, Partitioned partitioned) throws Throwable {
List<T> inputIds = (List) pjp.getArgs()[0];
if (inputIds.size() > partitioned.size()) {
List<D> dataList = new ArrayList<>();
Collection<List<T>> partitionedIds = PartitionArray.partitionBasedOnSize(inputIds, partitioned.size());
for (List<T> idList : partitionedIds) {
List<D> data = (List) pjp.proceed(new Object[]{idList});
dataList.addAll(data);
}
return dataList;
}
return pjp.proceed();
}
}
Of course you have to import AspectJ, and also do some additional stuff at compile-time. Assuming you are using maven, add those lines to your pom.xml
(plugin and dependencies):
<build>
<plugins>
...
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.7</version>
<configuration>
<complianceLevel>1.8</complianceLevel>
<source>1.8</source>
<target>1.8</target>
<showWeaveInfo>true</showWeaveInfo>
<verbose>true</verbose>
<Xlint>ignore</Xlint>
<encoding>UTF-8</encoding>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
...
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${aspectj.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectj.version}</version>
</dependency>
...
</dependencies>
>` (even maintaining the order)
– Holger Oct 15 '18 at 15:38