aspectj , What do return statements do in an AspectJ advice?

What do return statements do in an AspectJ advice?


Tag: aspectj

The following is an excerpt from an AspectJ example:

class Point  {
      int x, y;

      public void setX(int x) { this.x = x; }
      // ...

  aspect PointAssertions {

      private boolean Point.assertX(int x) {
          return (x <= 100 && x >= 0);
      // ...

      before(Point p, int x): target(p) && args(x) && call(void setX(int)) {
          if (!p.assertX(x)) {
              System.out.println("Illegal value for x"); return;
      // ...

Could someone please clarify for me what the return; statement does in the before advice - why it is (needs to be?) there and what would happen without it?

Will it basically "return form setX()" before the method body is executed?

Is there a manual page explaining it?


To complete the answer by @LajosArpad, before advices can only change the flow by throwing an exception. The only advice that can prevent calling the advised method while retaining the same flow semantics is around, but it needs to return something itself in that case (if the return type is not void, of course).


pointcut execution for specific class constructor

I'm trying to create specific class constructor pointcut execution but I get the following marker: Aspect code: public aspect CarLogger { private Logger logger; pointcut instantiate() : execution (; after() : instantiate(){ logger.log(Level.INFO, "In Car::Car()", thisJoinPoint.getThis()); } this code returns no match for this type name Car. But if I...

Spring Aspects (AspectJ) does not seem to work

Well I really don't know why this does not work: Every jar needed is in the place. Including aspectjrt. Basically I start with configuration class: @Configuration @ComponentScan(basePackages = { "some.path" }) @EnableAspectJAutoProxy public class SomeConf { ... } Then I have my Aspect: @Component @Aspect public class ControllerLoggerAspect { @Pointcut("execution(*...

Can you explain what AspectJ's cFlow(P && Q) does by means of example?

I'm currently going through AspectJ's documentation, and I don't quite get their point on Pointcut composition. In particular, I don't understand what cFlow(P && Q) does, when advice with that pointcut would get executed. A PowerPoint presentation (for a course at the university of Utrecht) I found explains cflow is...

How can I exclude getters and setters in aspectJ?

I have a class aspectJ in my maven project whitch hepls me to show the Begin and the End of any called method in my project. I try now to exclude all getters and setters. I try modify this annotation: @Around("execution(public * *(..)) by @Around("execution(public * *(..) && !within(* set*(..))")...

AspectJ - Cannot register non aspect error

I am trying to play with AspectJ and run time weaving. I have created an aspect @Aspect(value = "TraceAspect") public class TraceAspect { @Around("execution(* *(..))") public Object around(ProceedingJoinPoint invocation) throws Throwable{ System.out.println(String.format("Invocing %s", invocation.getSignature().getName())); try { Object ret = invocation.proceed(); System.out.println(String.format("Done Invocing %s", invocation.getSignature().getName())); return ret; } catch (Throwable throwable)...

Is it mandatory to implement concrete aspect in aspectJ

I am running a HelloWorld project using load time weaving (LTW) in aspectJ. I had defined abstract aspect only. I had not defined concrete aspect but mentioned "name" attribute of <concrete-aspect> as in the aop.xml as below: <concrete-aspect name="" extends=""> <pointcut name="helloWorld" expression="execution(public static void HelloWorld.say*(..))" /> </concrete-aspect> I...

Spring aspectj implications

I'm working on a project which has an aspect and has a @EnableAspectJ on a configuration. It means all proxies of spring are created using aspectj? What happen then with @Transactional and @Async? Should it has mode attribute set to use aspectJ ? Or it will uses CGLIB and Aspectj?...

Error while using aspectj with Scala

I am having an application in scala. I need to use AOP for one of the functionality. I used the plugin sbt-aspectj . Everything is working fine when I run using the sbt console. However, I am not able to make it work when using the executable jar. I tried...

Get Annotation Parameter with AspectJ

I read many question in this forum but nothing works. public @interface MyAnnotation { String value() default ""; Class[] exceptionList; } @MyAnnotation(value="hello", exceptionList={TimeOutException.class}) public void method() {} @Aspect public class MyAspect { @Around("@annotation(MyAnnotation)") public Object handle(ProceedingJoinPoint joinPoint, MyAnnotation myAnnotation) { System.out.println(myAnnotation.exceptionList); // should print out TimeOutException } } How can...

How do I get my Spring Aspect to kick in for a @Valid annotation on a service method?

We're using Spring 3.2.11.RELEASE and Maven 3.0.3. I'm trying to set up validation of a parameter being passed into a service method. The method is below. Notice the @Valid annotation. package org.mainco.subco.mypck.service; @Service @RemoteProxy @Transactional public class MypckServiceImpl implements MypckService { @RemoteMethod @Override public String myMethod(@Valid final MyObjectDto request) {...

Caused by: java.lang.ClassNotFoundException: org.aspectj.weaver.BCException in JBOSS AS

Currently, my application server does not start because it reports class not found when my dependencies are already exposed in the maven and bundled together in my ear. Basically how do you get JBOSS 7.1 to work with AspectJ smoothly. Maybe I need to add a module? An AspectJ module?...

AspectJ AWS Activity generation failing

I am currently using AspectJ to generate Client implementation code for my AWS Activity's. This has generally been working really well for both workflows and activitys. Its worth noting I don't know alot about AspectJ as I am only using it for this code generation. However I have reached a...

AspectJ not working after Transaction configuration in Spring Boot

Firstly i had a problem with Transactions not working so i updated the configutation from @EnableTransactionManagement to @EnableTransactionManagement(proxyTargetClass=true), but after the update this bug is thrown at launch. after commenting all code related to AspectJ, the bugs disappears and the transaction is working perfectly, but i'm missing my AspectJ functions....

Full support for JavaFX properties in POJOs

There are quite a few questions on SO regarding adding JavaFX property support to existing POJO classes. Properties for those classes can be created by using adapters in package. However, properties created in such way will not reflect changes made using setter methods of POJO classes, unless PropertyChangeSupport is...

What are benefits of using Aspectj in Spring config, if aspectj can be used alone

I looked at many Aspectj tutorials in web and most of them are: Aspectj config with Spring beans. Per my understanding, if I am using javaagent:./src/main/resources/aspectjweaver.jar and if I created aop.xml, aspectj weaving will work for all classes and objects (including those managed by Spring). Why do I need to...

Getting java.lang.ClassFormatError: Duplicate method name&signature in class file when implementing PERTHIS aspectJ implementation in Wildfly 8

I am using AspectJ as AOP API in my EAR project. The project contains EJBs and MBeans and running on Wildfly 8.2.0 application server. In AspectJ, there is an aspect association - perthis which I am trying to implement in my project. This aspect association will create new aspect instance...

How to get values of method's parameters?

I have the aspect: public aspect TestAspect { pointcut publicMethodExecuted(): execution(public !static * *(..)); int around() : publicMethodExecuted() { //I need parameters values here //to write their to log int original_return_value = proceed(); return original_return_value * 100; } } How to get parameters the method was called with? I need...

Is it possible to make JSF FacesServlet work with AspectJ?

I'm trying to write sample application showing the intergration between JSF's FacesServlet running on tomcat and AspectJ. I've created two projects: 1) JSF project: pom.xml: <dependencies> <!-- JSF 2.0 dependencies --> <dependency> <groupId>com.pac</groupId> <artifactId>aspectj-lib</artifactId> <version>1.0-SNAPSHOT</version> </dependency> </dependencies> <build> <finalName>JavaServerFaces</finalName> <plugins> <plugin>...

@AspectJ: Pointcut for any method of custom annotated class

I'm trying to detect in a pointcut any method of a class annotated with my annotation @NFCDisable. @NFCDisable public class MyClass { //methods } I have tried this: @Aspect public class NFCAspect { @Before("method()") public void exec() { //DO SOMETHING } @Pointcut("@within(NFCDisable) || @annotation(NFCDisable)") public void method() {} } But...

AspectJ: List pointcut args
I have this class: public class MyClass { public void updatePeople(List<Person> people) { //DO STUFF } } I want to log the size of people when updatePeople is called by AOP. This is my aspect: @Aspect public class MyAspect { @Pointcut("execution(void com.bla.bla.MyClass.updatePeople(List<Person>)) && args(people)") public void updatePeople(List<Person> people) {} @Before("updatePeople(people)")...

Tool for java that uses annotation to monitor/log/report threads accessing given method?

Context: I have created a small (java) multithread server for a game. Despite my best efforts of following the best practices it turned out that some methods that were intended to be called from just one thread got called from 2 or more threads. After debugging and analysis I have...

AOP (without Spring) not working on Tomcat but Eclipse

Implemented AOP using AspectJ without Spring. It works perfectly fine when running in Eclipse (Tomcat server) but not when run directly in Tomcat. Have added required dependencies in the pom but of no use. Not able to figure out the issue. Aspect class: @Aspect public class FeatureAOP { private static...

What do return statements do in an AspectJ advice?

The following is an excerpt from an AspectJ example: class Point { int x, y; public void setX(int x) { this.x = x; } // ... } aspect PointAssertions { private boolean Point.assertX(int x) { return (x <= 100 && x >= 0); } // ... before(Point p, int x):...

Cannot find parent aspect for concrete aspect

I have trying to test load time weaving in simple hello world normal Servlet based example in wildfly8.2 I have below Aspect code package com.test.aspects; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import com.test.helloworld.HelloService; @Aspect public abstract class FieldAspect { @Pointcut public abstract void getField(); @Pointcut public abstract void setField(); @Around("getField()")...

Eclipse not compiling because of ClassNotFoundException

After following an AWS tutorial for Eclipse, my code no longer compiles and runs. I decided to undo what the tutorial told me, so I may have changed some settings that I forgot to unchanged but I really cannot find the root of my problem. Eclipse seems to be back...

How can I use Equinox Weaving with bndtools

How can I use equinox Weaving with bndtools because the equinox Weaving example is old and can't get it to work? update: when trying to run the weaving sample for Hello world I have two bundles: public class HelloService implements BundleActivator { public void start(final BundleContext context) throws Exception {...

Get target Object in Aspect and call another method on target object

I want to write an aspect on a method pointcut, and in the aspect I want to call another method using the object on which pointcut method is called. Something like this: @Pointcut("@annotation(com.mypackage.Notify(getC))") public void notifyPointCut() { } @AfterReturning(value = "notifyPointCut(getC)", argNames = "joinPoint") public void notifyChange (JoinPoint joinPoint) {...

How to tell maven to compile a project as an aspectj project

My project: src/main/aspects: com |---badmitrii |---Trace.aj src/main/java: com |---badmitrii | I wrote the following pom: <project xmlns="" xmlns:xsi="" xsi:schemaLocation=""> <modelVersion>4.0.0</modelVersion> <groupId>com.badmitrii</groupId> <artifactId>aspectj-test</artifactId> <packaging>jar</packaging>...

Reading and understanding AspectJ pointcuts?

/* 0 */ pointcut services(Server s): target(s) && call(public * *(..)) This pointcut, named services, picks out those points in the execution of the program when Server objects have their public methods called. It also allows anyone using the services pointcut to access the Server object whose method is...

Get Spring Bean from AspectJ ProceedingJoinPoint

I'm looking to get the Spring Data Repository interface or the bean calling void delete(id) using AspectJ, the problem with that function is there is no argument or return type to guess the bean, is there any idea how to get the calling bean or the interface name from AspectJ...

Executing PointCut depending on Environment variable or property

I've developed a nice Spring Aspect which I can use to monitor my service operations performance. If some operations are taking a long time to execute, it logs them. @Aspect public class PerformanceMonitorAspect { private Logger logger = LoggerFactory.getLogger("performance"); @Pointcut("execution(**(..))") public void pointCut(){ } @Around("pointCut()") public Object profileServiceMethods(ProceedingJoinPoint thisJoinPoint)...

AspectJ not working with @Before

I have no idea why this simple application is not working. Everything is wire together correctly and I am not getting any errors. I am just trying to use AspectJ to call a method before another. package; import; public class App { public static void main(String[] args) {...

how capture the main method trace from jade using AspectJ?

i am using Jade in eclipse IDE, i want to capture the main method from jade, because the main method is the starting point for every application, i want to test if it is also right with the running of the JADE middleware (ie: i want to check if the...

How to use AspectJ for Loggin in a maven project?

I have a maven Java EE 6 project and I have into every methods a Logger information to show in the console the beginning with parameters and the end too. In some methods i forgot the make that so i want to use aspectJ to manage the beginning and the...

AspectJ annotations: Pointcut params

I'm trying to log a login action with AspectJ. I need to obtain the logged user. I tried this but it doesn't work. The joinpoint is never executed. @Aspect public class LoginActivityAspect { @Pointcut(value = "call(void && this(username)", argNames = "username") public void loginSuccess(String username) {} @Before(value = "loginSuccess(username)")...

Spring 4 + aspects

I have problem with aspects. They don't firing. I have small aspect: @Aspect @Component public class SynchronizingAspect { @Pointcut("execution(public * *(..))") @Around("synchronize() && @annotation(Synchronized)") public void synchronize(ProceedingJoinPoint joinPoint) throws Throwable { Logger.getGlobal().log(Level.SEVERE, "LOOOOOOOOL"); joinPoint.proceed(); } } and a method with annotation: @Synchronized @Transactional @Override public User create(Map<String, Object> values) {...

Is it possible to return value from Spring AspectJ?

I'm returning value from my controller. Let it be ResponseEntity<String> type. Controller returns: new ResponseEntity<String>("{\"msg\":\"success\"}",HttpStatus.OK); Following value goes to my spring aspect. I am receiving this object in following code: @AfterReturning(pointcut = "somePointcut()",returning = "retVal") public ResponseEntity<String> adviceTest3(Object retVal) { //here i have access to controller's object return new ResponseEntity<String>("{\"msg\":\"changed...

Mockito's spy does not work along with AspectJ using maven

I have the following test class and I'm using Mockito's spy. By running my unit test using Eclipse (right click->Run as unit test) all tests pass which means that eclipse build process using m2e and AJDT works fine. @RunWith(MockitoJUnitRunner.class) public class SampleTest { @Mock private AnotherClazz mockedClazz; @Spy @InjectMocks private...

AspectJ can't work on Scala function literal?

I have the following scala class and annotated aspectj class: package playasjectj import org.aspectj.lang.annotation.Pointcut import org.aspectj.lang.annotation.Aspect import org.aspectj.lang.annotation.Before class Entity { def foo(p:String):String ={ return p } def bar(handler:(String,String,Long)=>String):Unit={ handler("first", "second", 100L) } } object Entity { def main(args:Array[String]){ val inst = new Entity"we are the champion") val handler...

Spring aspect ordering

What would be the order of invocations on the "way in" if I have 3 aspects like: @Order(Ordered.HIGHEST_PRECEDENCE) public class Aspect1 public class Aspect2 @Order(Ordered.LOWEST_PRECEDENCE) public class Aspect3 so Aspect2 doesn't have any order annotation. It is clear that Aspect1 will be invoked before Aspect3, but does it mean that...

MoSKito: “advice defined in … has not been applied”

I am trying to use moSKito monitoring tool to follow this step-by-step guide. I've added those strings in pom.xml file: <dependency> <groupId>net.anotheria</groupId> <artifactId>moskito-core</artifactId> <version>2.5.5</version> </dependency> <dependency> <groupId>net.anotheria</groupId> <artifactId>moskito-aop</artifactId> <version>2.5.5</version> </dependency> ... <plugin> <groupId>org.codehaus.mojo</groupId>...

AspectJ matching return type as interface with generics

I'm trying to create an AspectJ to intercept the returning methods that has an interface with generics. This is my AspectJ @AspectJ public class MyAspect { @AfterReturning("execution(java.util.Collection+<mypackage.MyAbstractEntity+> mypackage.mvc.controllers..*.*(..))", returning = "list") public doStuff(JoinPoint j, Collection<MyAbstractEntity> list) { } } and this is my class that I want to "aspect": package...

How to add a field to a custom-annotated class using AspectJ

To add a field to some specific class with aspectj we do package com.test; public class MyClass { private String myField; } public aspect MyAspect { private String MyClass.myHiddenField; } How do we add a field to a class that is annotated with some custom annotation? example usage : if...

Spring boot + Spring security with AspectJ not working

I am trying to configure spring global method security with AspectJ advice mode so I can use @PreAuthorize annotations in all @Configurable annotated classes. This my java configs: @Configuration @EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true, mode = AdviceMode.ASPECTJ) public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration and: @EnableCaching @SpringBootApplication @EnableSpringConfigured @EnableTransactionManagement(mode = AdviceMode.ASPECTJ)...

Spring AOP use AspectJ to works or what?

I am studying Spring AOP and I have the following doubt. From what I know there are 2 ways to implement AOP behavior into a Java application that are: AspectJ: that is the first original AOP technology that uses byte code modification for aspect weaving. Spring AOP: Java-based AOP framework...

ApsectJ is throwing exception while adding @Transactional annotation

We are using AOP and everything works fine, I have added @Transactional. This is happening when i move from one method to another and i can't find any connection!! !!!! annotation and the application is not starting and throwing exception: Reason: Expected stackmap frame at this location. Bytecode: 0000000: 014e...

Spring - @Configurable classes in external JAR

I want to use spring dependency injection for my domain classes, that are possibly not created within spring context. That's why I have annotated these classes with @Configurable annotation and I try to setup load time weaving. My spring configuration is : @SpringBootApplication @EnableSpringConfigured @EnableAspectJAutoProxy @EnableCaching(mode = AdviceMode.ASPECTJ) @EnableLoadTimeWeaving public...

NoSuchMethodError with AspectJ

Note: this is a proof of concept implementation and not the final thing. i have 3rd. party add ons and i want to limit their usage of sound, e.g. limit the duration etc. (not possible with security manager). To achieve this i thought about replacing the return of AudioSystem.getLine() with...

declare ITD static method on multiple types

I would like to declare a static method (like void main(String..args)) on every subtype of my App class. public aspect Aspects pertypewithin(App+) { protected Class appClass; after() : staticinitialization(App+) && !staticinitialization(App) { StaticPart point = thisJoinPointStaticPart; Signature signature = point.getSignature(); Class declaringType = signature.getDeclaringType(); this.appClass = declaringType; } public static...

Difference between call and execution pointcuts in PHP?

In AOP in Java (AspectJ) when we talk about method pointcuts, we can differentiate them into two different sets: method call pointcuts and method execution pointcuts. Basing on these resources here on SO: execution Vs. call Join point Difference between call and execution in AOP And some AspectJ background, we...