Search code examples
springaspectj

Declare parents aspectj


Firstly I try xml configuration:

 <aop:aspect>
        <aop:declare-parents types-matching="DBOperations.ILearningData+" 
                             implement-interface="DBOperations.ISaveResults"
                             delegate-ref="saverExtension"/>
 </aop:aspect>

and it works good.

Now I try to make aspectj, which should do the same:

public aspect ASaveResults {

public ASaveResults() { }

declare parents : TSaveResults implements ILearningData;
}

where TSaveResults is the same as the bean "saverExtension".

I run my code:

    ...
@Value("#{learningData}")
protected ILearningData saver;
    ...
    ((ISaveResults)saver).saveResults();

and get the error:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: sun.proxy.$Proxy12 cannot be cast to DBOperations.ISaveResults

what is the problem with my aspectj?

Also I tried this code unsuccessfully:

public aspect ASaveResults {

    public ASaveResults() { }
    
    declare parents : ISaveResults implements ILearningData;
    
    public void saveResults() {
        System.out.println("saver aspect");
    }

}

Solution

  • What you used there is core aspectj, so if you want to use Spring AOP, but not xml config then this is what you should do (not tested):

    @Aspect
    public class ASaveResults {
    
       @DeclareParents(value="ISaveResults")
       public static ILearningData interf;
    
       public void saveResults() {
          System.out.println("saver aspect");
       }
    }