Skip to content

Load time weaving with AspectJ and Spring frameworks snippet

Daria edited this page Oct 30, 2015 · 2 revisions

##XML configuration

  1. Add dependencies:
    org.aspectj:aspectjweaver //this one is weaver itself
    org.springframework:spring-instrument // this one is for spring context load time weaving

  2. Add <context:load-time-weaver /> in spring context for enabling it

  3. Run configuration with java agents
    -javaagent:<path_to_dependency>\aspectjweaver-[version].jar
    -javaagent:<path_to_dependency>\spring-instrument-[spring-version].jar

  4. META-INF directory of project should contain xml config named 'aop.xml'. Snippet of it:

<aspectj>
    <aspects>
        <!-- declare existing aspects to the weaver -->
        <aspect name="org.ametiste.metrics.aop.ChronableAspect"/>
        <aspect name="org.ametiste.metrics.aop.TimeableAspect"/>
        <aspect name="org.ametiste.metrics.aop.ErrorCountableAspect"/>
        <aspect name="org.ametiste.metrics.aop.CountableAspect"/>
        <aspect name="org.ametiste.utility.xmas.aop.WeaverTestAspect"/>
         <!-- Of the set of aspects declared to the weaver
                   use aspects matching the type pattern "com..*" for weaving. -->
        <include within="com..*"/>
    </aspects>
 
    <weaver options="-verbose ">
        <include within="org.ametiste.utility.xmas.infrastructure.transaction.*"/>
        <include within="org.ametiste.metrics.aop.*"/>
        <include within="org.ametiste.utility.xmas.aop.*"/>
    </weaver>
</aspectj>

Where first part are aspects that are expected to be called in weaved classes. Instructions say 'include within' instruction can point to packages but in practice couldnt make it work. Second part are packages that contain classes to be compiled by weaver. Should contain both packages with aspects and with weaved client classes.

As for Spring 0.3.0 weaved aspects beans in spring configuration should have attribute 'factory-method="aspectOf" for initialization. Its adviced also to add 'depend-on' attribute for beans that should depend on weaved aspect in documentation however it wasnt tested in newer versions.