aspectj,spring-aop , Get Annotation Parameter with AspectJ

Get Annotation Parameter with AspectJ


Tag: aspectj,spring-aop

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() {}

public class MyAspect {
    public Object handle(ProceedingJoinPoint joinPoint, MyAnnotation myAnnotation) {
        System.out.println(myAnnotation.exceptionList); // should print out TimeOutException

How can I get the value and the exceptionList of the @MyAnnotation while executing the advice? I'm using Spring 4.0.6, AspectJ 1.7.4


The solution for this is making sure the advice method's parameter name match the parameter name in AspectJ expression. In my case, the advice method should look like this:

public class MyAspect {
    public Object handle(ProceedingJoinPoint joinPoint, MyAnnotation myAnnotation) {
        System.out.println(myAnnotation.exceptionList); // should print out TimeOutException


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...

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...

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...

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...

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...

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>...

I am getting error in Spring Configuration XML file:org.xml.sax.SAXParseException

I am using AOP and I am stuck with this error I can't fix. My Spring Configuration XML file is: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="" xmlns:xsi="" xmlns:aop="" xsi:schemaLocation="

@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...

How can I get HttpServletRequest and HttpServletResponse object in Spring AOP

I want to get the response object in spring AOP before advice. If the session is invalidate I want to redirect to the login page, but unable to get the HttpServletResponse object in the Before advice method. Tried with the following way. @Autowired private HttpServletResponse response; public void setResponse(HttpServletResponse response)...

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...

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...

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):...

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...

Aspect not being called in Spring test

I am using Spring 4.16 and i have my ValidationAspect, which validates methods arguments and throws ValidationException if is something wrong. This is being called when i run the server and send requests, but not when comes from the test: package com.example.movies.domain.aspect; ... @Aspect public class ValidationAspect { private final...

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>...

spring-security-core 2.0.3 spring-aop 2.0.8 cause NoSuchMethodError

Using Maven to build my project under windows works fine, but when deploy it to Linux servers via bamboo, on two servers it seems ok but on third server I get a NoSuchMethodError regarding one of the spring libs. İf i remowe spring-aop:jar from war it works. İf it is...

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...

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...

Spring AOP: Advice not called in abstract class

I am trying save some data after and whenever a getResponse() is called from an implementation of class DefaultRequestHandler. But this not work, what am I missing? @Aspect public abstract class RequestHandler { protected ServiceProvider response; protected ServiceProvider request; @Pointcut public abstract ServiceProvider getResponse(); @After("com.mypackage.RequestHandler.getResponse()") public void save(ServiceProvider request, ServiceProvider...

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) {...

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 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...

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>...

Why does not “@Transactional(propagation = propagation.NEVER)” work?

On the spring docs, for never propagation: Execute non-transactionally, throw an exception if a transaction exists. I wanted to try like following: @Transactional(propagation = Propagation.NEVER) public void getDeps(long ID) { System.out.println(databaseImp.getDepartmentByID(ID)); } @Transactional(propagation = Propagation.REQUIRED) public void allProcessOnDB_second(long ID) { getDeps(ID); operation(ID); } @Transactional public void operation(long id){ System.out.println(databaseImp.getDepartmentByID(id)); }...

Writing a precise pointcut expression

I am using Spring AOP for logging wherein I want to log input/output of all methods present in package. I have written following pointcut for target package. @Pointcut("within(com.mypackage.model.*)") public void allmethods(){}; My logging method is as below. @Before("allmethods()") public void LoggingAdviceBefore(JoinPoint joinPoint) { StringBuffer logMessage = new StringBuffer(); if(joinPoint !=...

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...

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...

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...

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 {...

How to use Sping AOP to run code before every call of service method in Servlet

i have some common code must be injected into service method of any servlet . Thus, i build a mother servlet SuperController : public class SuperController extends HttpServlet{ private HttpServletRequest lastRequest ; //........ public void service(HttpServletRequest req,HttpServletResponse res){ setLastRequest(req); // example of common code } } THen, all other servlets...

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...

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?...

Create Spring @Service instance with @Transactional methods manually from Java

Let's say there are @Service and @Repository interfaces like the following: @Repository public interface OrderDao extends JpaRepository<Order, Integer> { } public interface OrderService { void saveOrder(Order order); } @Service public class OrderServiceImpl implements OrderService { @Autowired private OrderDao orderDao; @Override @Transactional public void saveOrder(Order order) {; } } This...

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...

How to keep Method Parameters Names with Spring Aspect in Java 8

I've done what's necessary to get the parameters name in Java 8. When MyBean has no aspect on it, i get the names: 'first' and 'second'. But when the aspect is set the bean is marked as MyBean$$EnhancerBySpringCGLIB and all i have is : 'arg0' 'arg1' This test has been...

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 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...

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 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) {...

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...

Spring AOP not working, when the method is called internally within a bean

I have several Aspects coded in my application. All others works except for the following. Service Interface package com.enbiso.proj.estudo.system.service; ... public interface MessageService { ... Message reply(Message message); Message send(Message message); ... } Service Implementation package com.enbiso.proj.estudo.system.service.impl; .... @Service("messageService") public class MessageServiceImpl implements MessageService { ... @Override public Message reply(Message...

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...

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...

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)...