aspectj,spring-aop , Get Annotation Parameter with AspectJ


Get Annotation Parameter with AspectJ

Question:

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


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


Answer:

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:

@Aspect
public class MyAspect {
    @Around("@annotation(myAnnotation)")
    public Object handle(ProceedingJoinPoint joinPoint, MyAnnotation myAnnotation) {
        System.out.println(myAnnotation.exceptionList); // should print out TimeOutException
    }
}

Related:


Is it possible to make JSF FacesServlet work with AspectJ?


maven,jsf,tomcat,jsf-2,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>...

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


java,spring,transactions,aop,spring-aop
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) { orderDao.save(order); } } This...

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


java,spring,spring-boot,spring-aop
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...

@AspectJ: Pointcut for any method of custom annotated class


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

Spring 4 + aspects


spring,aspectj,spring-aop
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) {...

Aspect not being called in Spring test


java,spring,spring-aop,spring-test,spring-aspects
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...

NoSuchMethodError with AspectJ


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

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


java,aspectj
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 to keep Method Parameters Names with Spring Aspect in Java 8


java,spring,spring-aop
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...

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


java,spring,aspectj
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


aspectj,ejb-3.1,wildfly-8,mbeans
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...

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


linux,spring-security,spring-aop,bamboo,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...

Writing a precise pointcut expression


spring,spring-aop,pointcut
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 !=...

What do return statements do in an AspectJ advice?


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

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


java,spring,transactions,spring-aop,spring-annotations
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)); }...

AOP (without Spring) not working on Tomcat but Eclipse


java,tomcat,aop,aspectj
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...

Get Annotation Parameter with AspectJ


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() {} @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 use Sping AOP to run code before every call of service method in Servlet


servlets,spring-aop
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...

How can I get HttpServletRequest and HttpServletResponse object in Spring AOP


spring,spring-mvc,servlets,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)...

Reading and understanding AspectJ pointcuts?


java,aspectj,pointcut,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...

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


java,aspectj
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>...

Spring aspect ordering


spring,aspectj,spring-aop
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...

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


java,multithreading,thread-safety,aspectj
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...

Executing PointCut depending on Environment variable or property


java,eclipse,spring,aspectj,spring-aop
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(* com.company.MyService+.*(..))") public void pointCut(){ } @Around("pointCut()") public Object profileServiceMethods(ProceedingJoinPoint thisJoinPoint)...

How to get values of method's parameters?


java,methods,aspectj
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...

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


java,spring,spring-aop
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="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop...

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


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

how capture the main method trace from jade using AspectJ?


jade,aspectj,agents-jade
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 can I use Equinox Weaving with bndtools


osgi,aspectj,equinox,load-time-weaving,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 {...

AspectJ AWS Activity generation failing


java,amazon-web-services,aspectj,amazon-swf
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...

Get Spring Bean from AspectJ ProceedingJoinPoint


spring,spring-boot,spring-data,aspectj
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...

Error while using aspectj with Scala


scala,sbt,aspectj,sbt-aspectj
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...

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


unit-testing,maven,mockito,aspectj
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...

Full support for JavaFX properties in POJOs


java,properties,javafx,aspectj
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 javafx.beans.property.adapter package. However, properties created in such way will not reflect changes made using setter methods of POJO classes, unless PropertyChangeSupport is...

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


java,maven,jboss,aspectj,spring-aop
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 can't work on Scala function literal?


scala,aspectj,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 inst.foo("we are the champion") val handler...

AspectJ not working with @Before


java,aspectj
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 com.springpractice.app; import org.springframework.context.support.ClassPathXmlApplicationContext; public class App { public static void main(String[] args) {...

Eclipse not compiling because of ClassNotFoundException


java,eclipse,amazon-web-services,compilation,aspectj
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 to tell maven to compile a project as an aspectj project


java,maven,aspectj
My project: src/main/aspects: com |---badmitrii |---Trace.aj src/main/java: com |---badmitrii |---App.java I wrote the following pom: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.badmitrii</groupId> <artifactId>aspectj-test</artifactId> <packaging>jar</packaging>...

declare ITD static method on multiple types


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

Spring AOP: Advice not called in abstract class


java,spring,spring-aop
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...

pointcut execution for specific class constructor


java,aop,aspectj,pointcut
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 (Car.new(..)); after() : instantiate(){ logger.log(Level.INFO, "In Car::Car()", thisJoinPoint.getThis()); } this code returns no match for this type name Car. But if I...

AspectJ matching return type as interface with generics


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


java,spring,aop,aspectj,spring-aop
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...