Search code examples
javaspringaspectjspring-roo

How to call method in file .aj in spring roo project?


How to call method in file .aj in spring roo project?

e.g. How to call method "Employee.findAllEmployees()" in Employee_Roo_Jpa_ActiveRecord.aj from method callMethod() in Employee.java?

file: Employee.java

  1 package com.tap.domain;
  2 
  3 import java.text.SimpleDateFormat;
  4 import java.util.ArrayList;
  5 import java.util.Calendar;
  6 
  7 import javax.validation.constraints.Max;
  8 import javax.validation.constraints.Min;
  9 
 10 import org.aspectj.lang.annotation.Aspect;
 11 import org.springframework.beans.factory.annotation.Value;
 12 import org.springframework.roo.addon.javabean.RooJavaBean;
 13 import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
 14 import org.springframework.roo.addon.tostring.RooToString;
 15 import org.springframework.stereotype.Component;
 16 
 17 @RooJavaBean
 18 @RooToString
 19 @RooJpaActiveRecord
 20 @Component("employee")
 21 public class Employee {
 22 
 23     private long id;
 24 
 25     private String name;
 26 public void callMethod() {
...
...
 30 }

file:Employee_Roo_Jpa_ActiveRecord.aj

  6 import java.util.List;
  7 import javax.persistence.EntityManager;
  8 import javax.persistence.PersistenceContext;
  9 import org.springframework.transaction.annotation.Transactional;
 10 import com.tap.domain.Employee;
 11 
 12 privileged aspect Employee_Roo_Jpa_ActiveRecord {
 13 
 14     @PersistenceContext
 15     transient EntityManager Employee.entityManager;
...
 27     public static List<Employee> Employee.findAllEmployees() {
 28         return entityManager().createQuery("SELECT o FROM Employee o", Emplo    yee.class).getResultList();
 29     }
...

Solution

  • The mechanism Roo uses is AspectJ's inter-type declaration.

    Basically: your employee class will have the findAllEmployees() method at runtime, so you can just call it:

    public void callMethod() {
        List<Employee> allEmployees = findAllEmployees();
        // now do something with the employees
    }