Spring AOP logging - spring-boot

I have a j2ee web application running on Spring framework. I want to implement logging using log4j and Spring's AOP. I am able to log the public methods using custom annotation. I am not able to log private methods using custom annotation. can any one please give reference how to implement custom annotation for private methods.

Spring AOP
Spring AOP doesn't support interception of private methods.
11. Supported Pointcut Designators
Due to the proxy-based nature of Spring’s AOP framework, calls within the target object are by definition not intercepted. For JDK proxies, only public interface method calls on the proxy can be intercepted. With CGLIB, public and protected method calls on the proxy will be intercepted, and even package-visible methods if necessary. However, common interactions through proxies should always be designed through public signatures.
Note that pointcut definitions are generally matched against any intercepted method. If a pointcut is strictly meant to be public-only, even in a CGLIB proxy scenario with potential non-public interactions through proxies, it needs to be defined accordingly.
If your interception needs include method calls or even constructors within the target class, consider the use of Spring-driven native AspectJ weaving instead of Spring’s proxy-based AOP framework. This constitutes a different mode of AOP usage with different characteristics, so be sure to make yourself familiar with weaving first before making a decision.
AspectJ Source Weaving
You can intercept private methods by taking advantage of AspectJ source weaving. Here is a complete working example.

Related

Spring #Transactional - synchronize via AspectJ

I am trying to synchronize declarative transactions (i.e. methods annotated with #Transactional) using AspectJ like so:
...
import org.aspectj.lang.annotation.Aspect;
...
#Component
#Aspect
public class TransactionMonitor extends TransactionSynchronizationAdapter {
#Before("execution(#org.springframework.transaction.annotation.Transactional * *.*(..))")
private void registerTransactionSynchronizationOnAnnotation(JoinPoint joinPoint) {
TransactionSynchronizationManager.registerSynchronization(this);
}
}
This currently fails with java.lang.IllegalStateException: Transaction synchronization is not active which indicates that the synchronization is not run inside the transaction execution, but before. I want to ensure that this is the other way round, of course.
I found this answer, however #Order(Ordered.LOWEST_PRECEDENCE) had no effect, and
#DeclarePrecedence(
"org.springframework.transaction.aspectj.AnnotationTransactionAspect, xxx.xxx.TransactionMonitor, *"
)
led to this during startup:
java.lang.IllegalArgumentException: DeclarePrecedence not presently supported in Spring AOP
I have the feeling this is AOP and AspectJ not being happy with each other, but I am not sure. I am thankful for any ideas.
EDIT: I have to use #EnableTransactionManagement(proxyTargetClass = true), can this be related to the issue?
For #DeclarePrecedence you need to switch to native AspectJ. Spring AOP is just "AOP lite" and technologically has little in common with AspectJ other than its syntax which is basically an AspectJ subset. The Spring manual describes how to use native AspectJ in Spring via LTW (load-time weaving). Precedence declaration for Spring components rather works using #Order, BTW.
I am not a Spring user at all, but as for declarative transaction management, it already knows proxy-based Spring AOP versus native AspectJ mode, see EnableTransactionManagement.mode and the enum constants in AdviceMode. Besides, EnableTransactionManagement also has an order property. Reading Javadoc and the Spring manual helps, I guess.

Spring AOP pointcut expression syntax for wildcard

I'm currently using AspectJ 1.6.9 and i wonder why the following pointcut expression:
(execution (* it.dtt..endpoint.*..*.invoke*(..)))
doesn't match the execution of the method declared:
protected Object invokeInternal(Object object) throws Exception
of the class:
it.dtt.prova.endpoint.Richiesta
any idea?
"Due to the proxy-based nature of Spring's AOP , protected methods are by définition not intercepted".
you need to change the access modifier of that method to public or consider use the spring-driven native AspectJ weaving
Spring docs:
Due to the proxy-based nature of Spring's AOP framework, protected
methods are by definition not intercepted, neither for JDK proxies
(where this isn't applicable) nor for CGLIB proxies (where this is
technically possible but not recommendable for AOP purposes). As a
consequence, any given pointcut will be matched against public methods
only!
If your interception needs include protected/private methods or even
constructors, consider the use of Spring-driven native AspectJ weaving
instead of Spring's proxy-based AOP framework. This constitutes a
different mode of AOP usage with different characteristics, so be sure
to make yourself familiar with weaving first before making a decision.

Spring AOP Method Interceptor vs Method Advice

I am new to AOP and I am trying to understand the difference between Method Interceptor and MethodAdvice(i.e. MethodBeforeAdvice or MethodAfterAdvice). To me looks like both are doing the same thing i.e. are called on method invocation. When should we use MethodInterceptor vs MethodAdvice.
Take a look at the definition of the org.aopalliance.interceptInterceptor interface (implemented by MethodInterceptor):
public interface Interceptor extends Advice {
}
It's easy to see that a MethodInterceptor actually IS an Advice.
The only difference between an Advice being defined in an #Aspect class and such an Interceptor is that Interceptor implementations can be added to and removed from Spring AOP Proxies at runtime (casting them to 'Advised'), whereas the Advice you're talking about is a more static construct. But their still essential to Spring AOP since their presence tells Spring which beans to wrap in a proxy object during application context startup.

Using Spring AOP uses underneath aspectj?

Hy,
Reading a lot about Spring AOP vs AspectJ, I still have some doubts:
1.)When using Spring AOP with classes annotated with #Aspect and using "aop:aspectj-autoproxy" tag , it can be said that we are using just the annotations of aspectj or besides that it is being used AspectJ too for the weaving?
2) Its said that AspectJ has better performance because the weaving is in compilation time, it means that the target class files are physically changed inserting the aspects in them? is it not a bit aggressive?
3)It said that Spring uses proxys for AOP, so, I undertand that when you get a bean from Spring, Spring builds a proxy in memory that has already inserted the aspects in it, right?
So why is it said that when a method from your proxy bean calls other method in the proxy, the last method will not have aspects?
Thanks
1) using aspectj-autoproxy means that #Aspectannotations are recognized, but Spring proxies are still being created, see this quote from the documentation:
Do not be misled by the name of the element:
using it will result in the creation of Spring AOP proxies. The
#AspectJ style of aspect declaration is just being used here, but the
AspectJ runtime is not involved.
2) AspectJ supports load time weaving, byte code weaving and compile time weaving. There should no difference in performance, it's just a different point in time to weave the aspect in (compilation, third party jars available, class load time), see this answer for further details.
It is actually more transparent once it's set up to have the aspects weaved at these moments, with runtime proxies there are problems when a bean calls itself using this.someMethod, the aspects don't get applied because the proxies get bypassed (#Transactional/#Secured does not work, etc.).
3) Have a look at this picture from the documentation:
With runtime proxies (non AspectJ), Spring leaves the bean class untouched. What it does is it creates a proxy that either implements the same interface as the bean (JDK proxy), or if the bean implements no interface then it dynamically creates a proxy class with CGLIB (subclass of bean).
But in both cases a proxy is created that delegates the calls to the actual bean instance. So when the bean call this.methodB() from methodA, the proxy is bypassed because the call is made directly on the bean and not on the proxy.
Spring AOP can be configured with AspectJ-sytle, ie annotations are parsed to build configuration but AspectJ compiler is not used for weaving. Only a subset of AspectJ annotations and poincut definitions can be used with Spring AOP.
Maybe, but I don't know any class that has complained. However, is possible that some classes don't allow re-weaving when modified by other bytecode tools.
Inner calls are not proxied because they call on this.method() (with this = the target bean begin proxied) and not on proxy.method() so the proxy has no chances to intercept the call. However, Spring AOP proxies usually notices when a target method return this and return itself instead, so calls like builder.withColor(Color.RED).withHat(Hat.Cowboy) will work. Note that in Spring AOP there are always two classes involved: the proxy and the target.

Spring application has Cglib2AopProxy warnings

Upon starting my application, I get numerous warnings along the lines of o.s.aop.framework.Cglib2AopProxy 'Unable to proxy method [public final void org.springframework.jdbc.core.support.JdbcDaoSupport.setDataSource(javax.sql.DataSource)] because it is final: All calls to this method via a proxy will be routed directly to the proxy.' for about a dozen or so functions.
Now I perfectly understand that proxy-based aspects cannot be applied to final methods. However, I did not (on purpose, at least) try to weave any aspects into JdbcDaoSupport. I suspect it comes from <tx:annotation-driven />. Is there anything I can do to silence these warnings or, better yet, exclude those classes from the aspect weaving?
This is most likely caused by the #Transactional annotation, Spring wraps your DAO in a proxy to add the transactional behavior.
I would recommend to make your DAO implement an Interface (create and use an interface for your DAO), this will allow Spring to use a JDK dynamic proxy instead of having to use CGLib.
Using CGLIB has a limitation that methods marked as final in target class can’t be advised as final methods can’t be overridden (CGLIB creates a subclass of target class at runtime) but this limitation disappears in case of using JDK dynamic proxies.
Reference
Maybe you have extended JdbcDaoSupport and added #Transactional annotations.
You can set the Cglib2AopProxy logger to log level ERROR to avoid the warn messages. For example if using log4j and log4j.properties:
log.logger.org.springframework.aop.framework.Cglib2AopProxy = ERROR
You should use interfaces for dependency injection, the most reasons for this are described here and here.
You can read documentation about proxying mechanic for details why you see this warning.
And please vote for feature request of inspection for IntelliJ that may helps us to avoid this warnings. BTW It also contains a good explanation.
Spring Boot now uses CGLIB proxying by default, including for the AOP support. If you need interface-based proxy, you’ll need to set the spring.aop.proxy-target-class to false.
spring.aop.proxy-target-class=false

Resources