What is 'weaving'? - spring

I've seen this term when read about how Spring works and I've just read the article about JPA implementation performance and it has the next statistics:
EclipseLink 3215 ms
(Run-time weaver - Spring ReflectiveLoadTimeWeaver weaver )
EclipseLink (Build-time weaving) 3571 ms
EclipseLink (No weaving) 3996 ms
So, could someone explain in plain English, what is weaving?
Thanks!

Weaving is generating or editing code by directly modifying existing .class (byte-code) files.
This can occur at different points in the application life cycle.
Outside of JVM
at compile time
at packaging time
Inside a JVM
at class load time.
after a class has been loaded.
Spring Framework uses this for AOP functionality. Eclipselink uses weaving for lazy loading or change tracking.

From here:
In Spring AOP makes it possible to modularize and separate logging, transaction like services and apply them declaratively to the components Hence programmer can focus on specific concerns. Aspects are wired into objects in the spring XML file in the way as JavaBean. This process is known as 'Weaving'.

In nutshell, we could say
Weaving is the process of applying the Advices to the Target objects
at given pointcuts to get the Proxy Objects.

I‌ found this description useful:
Weaving: This is the process of inserting aspects into the application code at the
appropriate point. For compile-time AOP solutions, this weaving is generally done
at build time. Likewise, for runtime AOP solutions, the weaving process is executed
dynamically at runtime [using JDK‌ dynamic proxy and CGLIB proxy]. AspectJ supports another weaving mechanism called load-
time weaving (LTW), in which it intercepts the underlying JVM class loader and
provides weaving to the bytecode when it is being loaded by the class loader.
reference: Pro Spring 5: An In-Depth Guide to the Spring Framework and Its Tools

Object-oriented software systems that are developed
using aspect-oriented programming techniques
consist of classes and aspects. Classes implement
the primary functionality of an application,
for example, managing stocks or calculating
insurance rates. Aspects, on the other hand, capture
technical concerns like persistence, failure handling,
communication, or process synchronization.
There are two ways in which classes and aspects
can be woven: static or dynamic.
Static weaving means to modify the source code of a class by inserting aspect-specic statements at
join points.In other
words: aspect code is inlined into classes. The
result is highly optimized woven code, whose execution
speed is comparable to that of code written
without using aspects.

Weaving is a technique of manipulating the byte-code of compiled Java classes.
Ref: http://www.eclipse.org/eclipselink/documentation/2.5/concepts/app_dev007.htm
Cheers!

Weaving is the process of linking aspect with other application types or objects to create an advised object. Weaving can be done at compile time, load time or runtime. Spring AOP performs weaving at runtime.

Related

Why is load time weaving using aspectjweaver javaagent so slow for me?

The project I'm working on is considerably large. While trying to get load time weaving working for this spring project, I was instructed to use both the spring-instrument javaagent as well as the aspectjweaver javaagent. However, I notice that when using the aspectjweaver agent, my launch time shoots up 4-6 fold. I can also see identical weave messages 4-6 times coming from ContextOverridingClassLoader.
If I remove aspectjweaver however, and only use spring-instrument, I notice my launch time decrease dramatically with only a single weave message per join point coming from AppClassLoader.
The only issue being that some specific classes are not woven (I found that this is due to the spring application context not yet being loaded before the faulty classes are loaded by the class loader, as spring is the mechanism that enables the weaving). I've found a solution of my own by creating a custom javaagent which enables weaving in the same manner that spring-instrument does, only it does so in the premain rather than on application context load. It now weaves all the classes and in reasonable time.
However, I'd prefer not to go down this hacky road as I can only presume that the two agents were designed the way it is for a reason.
I wonder if anyone else has seen a similar issue with the aspectjweaver javaagent and if someone might know why that agent is so slow compared to just using spring-instrument.
If the answer interests anyone, I've figured out the issue.
Spring uses a temporary classloader ContextOverridingClassLoader to get metadata about the bean classes prior to actually loading them into the context.
The spring-instrument javaagent (or more accurately, the spring framework code which may or may not use the spring-instrument javaagent) specifically only weaves classes loaded by the classloader used to load the application context.
Code inside of InstrumentationLoadTimeWeaver$FilteringClassFileTransformer:
if (!this.targetClassLoader.equals(loader)) {
return null;
}
return this.targetTransformer.transform(
loader, className, classBeingRedefined, protectionDomain, classfileBuffer);
On the other hand, aspectjweaver does not have such a filtering mechanism and so will weave even those classes loaded by spring's temporary ContextOverridingClassLoader. Fortunately, aspectjweaver has an essentially undocumented system property (or at least I was unable to find any documentation on this) called aj.weaving.loadersToSkip. By setting this to:
-Daj.weaving.loadersToSkip=org.springframework.context.support.ContextTypeMatchClassLoader$ContextOverridingClassLoader
I was able to skip weaving for that classloader and speed up the loading of my application context tremendously.
Incidentally, I've found that both the spring-instrument and aspectjweaver ultimately both use ClassPreProcessorAgentAdapter to weave the classes, and thus it is probably not necessary to use both agents (aspectjweaver will weave a superset of the classes that spring-instrument will). However, depending on your configuration, the application might complain about the missing agent at startup so you might as well include it (at the cost of some additional unnecessary overhead).

AspectJ in Spring: CTW vs LTW

Question regarding AspectJ in Spring: CTW vs LTW. What's the difference? As far i understand the both approaches make the same - they both are producing java class with incorporated aspect logic instead of original class. CTW do it during compile time, LTW do it during JVM loading classes. Could you please explain any other diff between them? Thank you in advance!
First of all, AspectJ is independent of Spring. It was invented before Spring and does not need any frameworks. Maybe you are unaware of the difference between Spring AOP (based on dynamic proxies) and AspectJ (based on byte code instrumentation). By default you would not use CTW or LTW in Spring but just simply Spring AOP. Only if this "AOP lite" approach is not powerful enough for you, you will use the full power of AspectJ with or without Spring.
Please read the Spring AOP manual in order to learn how to use it. There is also a chapter on AspectJ there for you to study.
Concerning the basic technical differences with between types of AOP like CTW, LTW, proxy-based incl. pros and cons, see my answer there. #Moderators: I really do not want to quote myself here, but also not flag this question as a complete duplicate.
I tried to use LTW a long time ago and it had some bugs as sometimes on startup it failed to do the weaving which is pretty bad and I decided to use CTW from then on.
LTW increases startup time but is probably easier to debug in intellij/eclipse while with CTW debugging might be hard to setup sometimes.
But as I said CTW is safer for me - classes are there ready to go, no surprises during startup/runtime. So if you do not do dynamic class loading (like in OSGi or similar) and want to weave that code with aspects then I would stick to CTW.

Using aspects written with AspectJ in projects which use Spring AOP

I'm new in Gradle/AspectJ and I have a few questions regarding this.
I develop some library which will be used in other projects. I use AspectJ to implement some cross-cutting logic and I created my aspects using #Aspect without apectj specific language.
This lib is small framework which provides some annotations to use it.
I created unit tests for my classes. I know that to apply aspects I need to compile classes using AspectJ compiler ("ajc"). In my ide I run tests with option: -javaagent:[path to aspectjweaver jar] and all my tests are working well as excpected. But when I run tests from gradle then some tests are failed because my aspects aren't applied. I heard about aspectj plugin in maven and tried to find something similar for gradle. I found this plugin which weaves AspectJ aspects into classes and it works good, all tests are passed, but I faced with some problems. How I said I develop third-party lib which used in other projects, if some projects use Spring AOP then my aspect doesn't work. For example aspect isn't apply with next configuration:
<aop:aspectj-autoproxy/>
<bean id="myAspect" class="com.ext.aop.MyAspect"/>
To make it clear my aspect wraps all methods which annotated with my specific annotation in some logic, that's all.
In the case of Load-time weaving my aspects are working:
<context:load-time-weaver aspectj-weaving="autodetect"/>
-javaagent:lib/spring-instrument.jar
Maybe somebody know what's the problem ? How I understand in the case of LTW the project's developers need to compile project with using some plugin again in order to wave acpects. Whether the use of LTW affect other aspects which already exist in a project? Maybe there is a way to say gradle to wave aspects only for tests and leave project's developers to be responsible for compiling aspects in an appropriate way? Or better create separate version of lib for spring framework? Maybe someone encountered such situation and have any ideas, so please give me advice. Thanks for advance.
Spring AOP cannot process a aspects which were compiled by ajc, the snippet from AbstractAspectJAdvisorFactory source:
/**
* We consider something to be an AspectJ aspect suitable for use by the Spring AOP system
* if it has the #Aspect annotation, and was not compiled by ajc. The reason for this latter test
* is that aspects written in the code-style (AspectJ language) also have the annotation present
* when compiled by ajc with the -1.5 flag, yet they cannot be consumed by Spring AOP.
*/
public boolean isAspect(Class<?> clazz) {
return (hasAspectAnnotation(clazz) && !compiledByAjc(clazz));
}
I guess you should provides pure acpects (java classes compiled only by javac) to give others a chance to compile it as needed. But I recommend you to create tests for all possibles use cases: using your lib together with spring aop, acpectj, guice aop and etc.

Spring AOP vs #Transactional annotation

I want to implement transaction using Spring's transaction management feature. But I'm not sure which is better(AOP vs #Transactional). Do both features work correctly? Is there any difference in development efficiency?
(Added)
Here AOP means "using AspectJ without using #Transactional annotation explicitly"
(Added)
I want to know difference of annotation-config and XML-based configuration
I've wondered this myself. I found a good discussion of this topic on the Spring forum.
Below I've summarize my take from the aforementioned link:
AOP Transactional Demarcation
Benefits:
Java code is devoid of transaction configuration which is contained instead outside of the code in configuration files
Java code has no direct dependencies on Spring libraries
Transaction management is centralized in one place
Can apply transactional boundaries to source code you can't easily modify
Drawbacks:
AOP complexity. It will not be clear from the code alone where transactional boundaries lie and developers may inadvertently break transactions by, for example, modifying method signatures where a pointcut is applied
The need to touch two locations (source code and AOP configuration) in order to apply transactional boundaries
#Transactional Spring annotation
Benefits:
Transactional boundaries are more clearly understood when examining the source code
Drawbacks:
Java code is coupled with transaction declaration (albeit only at the metadata level, but still a Spring import is required).
The discussion reminds me of JPA annotations versus JPA XML configuration. With XML based JPA configuration, entities are "cleaner", but is the separation worth the effort? Or perhaps even, is the separation harmful (it's nice to be able to open a java source file and know immediately based on the #Entity annotation that the class is an EJB)? In practice, it seems to me that most developers opt to use JPA annotations. Although, in this case unlike #Transactional, jpa annotations are a standard so that may help ease some concerns.
That said, I've been involved on projects were we've used Spring's AOP configuration to annotate a Struts2 (webwork) interceptor to allow a single transaction per request and this worked out great. In this case, we didn't really worry about transactional boundaries in our service layer or elsewhere -- everything was already participating in a transaction and since the view rendered before the interceptor closed the transaction, there was no need to apply an OpenSession/EntityManagerInView solution.

Difference between Spring IOC and Spring AOP

What is the Difference between Spring IOC and Spring AOP and their Importance ?
Have you searched the web for IoC and AOP? There are a lot of references to both.
In a nutshell, IoC allows an external force to determine what implementation will be used by code rather than the code determining the implementation. The "external force" might be a configuration file, a unit test, other different code, etc.
AOP allows cross-cutting concerns to be implemented outside of the code affected by those concerns.
The "purpose" of Spring includes IoC and AOP, but goes quite a ways beyond that in its scope.
For more details please check.
Inversion of Control Containers and the Dependency Injection pattern and
Aspect-oriented programming
Also check this
What is AOP, Dependency Injection and Inversion Of Control in Simple English
IoC, AOP and more
Spring IOC: In simple answer normally you create object with new operator and set yourself for getter and setter. So, yes we use new operator in Java to create object. There is no any bad in doing this. But, when your project size grows and lots of developers are working, and you want to achieve POJO-based programming, you can use DI. So then maybe your question arises - why I can not code it myself? Of course you can use the power of reflection, annotation, and XML. But, some other had already coded this then why not reuse the third party one? There are lots of options for you to choose; Spring can be the best one. It manages your object life cycle from object creation to its destruction. You use the objects created and set by Spring DI container but you do not create them yourself.
Spring AOP: It is related to cross cutting concern. What it mean is in large system the common functionality is scattered throughout different modules. So AOP provides an easiest way to take out a common implementation in the form of 'aspect'. You can also in this case write own implementation using proxy concept but you can reuse the code of proxy based that is implementation of APO alliance using Spring.
Objective of Spring IOC is to reduce explicit dependencies between components, while purpose of Spring AOP is to wire components together possibly by enforcing certain common behavior (read: NOT Interface)
Since purpose of Spring AOP is to enforce certain behavior across components.So, Spring IOC comes in handy to achieve this purpose

Resources