Spring AOP: Disadvantages when using it - Spring Features which use Spring AOP do not have this disadvantages? - spring

Im working with the Spring Framework 3.0.5 and Spring Security 3.0.5 and Ive got questions to the aspect orientated programming. At the moment Im trying to figure out the disadvantages and advantages of aspect orientated programming. Of course, I know them in theory: I can avoid redundant code, I only have to make changes in the aspect, not everywhere in the code and so on. But I still got some questions:
The disadvantage I found out:
I wrote a sample application using aspects with Spring AOP. I configured an Aspect with Annotations (#Pointcut, #Before, #Aspect and so one). The methods that triggered the aspect (which were part of a Pointcut of course) were of course part of a different class and not annotated with anything.
=> I really think that one big disadvantage is that when watching those methods of the other class it was not clear that they trigger an aspect. They needed no annotations or anything else, they were just mentioned in the pointcut of the aspect. (I really hope you understand what I mean). So thats why I think that AOP makes code also less understandable!
a) Is there a solution to this problem? (Can this maybe be solved when I put the whole configuration in an XML File? I dont think so.)
b) Would this problem still exist when I would use AspectJ instead of Spring AOP?
Springs Features using Spring AOP: they dont have this disadvantage?
As Spring AOP is part of many Spring Features (just like declarative Transaction Management or (maybe) Spring Security(?)) I took a closer look at those Features. I was not able to find any disadvantage at all.
c) Lets take the declarative transaction management as an example: managing transactions is so easy with those annotations (#transactional) and I dont really find the disadvantage I mentioned above. I can see the methods that trigger specific behaviour. (all #transactional methods trigger transactional behaviour) Maybe I misunderstood something and this isnt where AOP is used? But if I did not misunderstood this, why is it here possible to see which methods trigger aspects and why isnt it possible to see in my example above? I would really like to know this!
Thank you for answering! :-)
EDIT: a) and b) are answered (use an IDE which marks those methods), c) is still missing :-)

For Point b)
If you use an Eclipse with Spring IDE and AspectJ plugin, or STS, the IDE will show you where Aspects are woven in.
For Point b)
If you use AspectJ and an IDE that supports AspectJ (Eclipse with AspectJ Plugin, or STS), then you will see markers in the souce-code where the Aspect is woven in.
An disadvantaged of Compile time AspectJ is, that you are not able to wove aspects in libraries. (without advanced techniques).
For Point c)
There is only one disadvantage of declarative Aspects like #Transactional. -- You can forget to put the annotation on the method.
But if you have for example a rule like: every public method in a Class annoteted by #Service (or if you like to build you own #TransactionalService), is transactional, then you do not need to specifiy the #Transactional annotation on each method. -- So in Summary: declarative Aspects are very good for reading (you will not overlook them), and they are good if your code is very (lets say) "individual" (instead of the term "not consistent") . But If you work in an Environment with Strong Architecural Rules (like every public method in a #Service class...), then you can Write this rules down in a Point Cut Definition, instead of using declarative Aspects.

Actually for point a) the same answer holds that Ralph gave: use Eclipse with either AspectJ plugin or if you are using Spring anyway, use STS.
That way you will see in your IDE if a certain method matches a pointcut on the left side of your editor, represented by small red arrows:

Actually, Spring AOP supports creating custom annotations.
I defined a annotation named Loggable binding with Advice.The Loggabel could be applied to any method you want.
public #interface Loggable {
}
#Aspect
public class EmployeeAnnotationAspect {
#Before("#annotation(com.ben.seal.spring.aspect.Loggable)")
public void myAdvice(){
System.out.println("Executing myAdvice!!");
}
}

Related

Where I can find the implementation of Autowired Annotation in Spring?

I want to implement my own custom annotations, that is why I am looking for Spring annotations' implementation. Which code executes behind the screen when we use an annotation?
Definition of an annotation is pretty simple. You can find definition of #Autowired annotation here:
https://github.com/spring-projects/spring-framework/blob/master/spring-beans/src/main/java/org/springframework/beans/factory/annotation/Autowired.java
If you're interested in its processing, you can clone spring-framework repository and search for its usage in the code of Spring.
If you want to implement your own custom annotation processor, I'd recommend to search for simpler examples than Spring and #Autowired.
I'm also planning to play around with annotation processors and I collected a few links related to this topic. Maybe you'll find them useful.
Java related:
https://github.com/bozaro/example-annotation-processor
https://github.com/eugenp/tutorials/tree/master/annotations
http://www.baeldung.com/java-annotation-processing-builder
https://www.gesellix.net/post/providedcompile-and-compile-dependencies-with-gradle/
http://programmaticallyspeaking.com/playing-with-java-annotation-processing.html
https://github.com/Jimdo/gradle-apt-plugin
http://mrhaki.blogspot.com/2016/03/gradle-goodness-enable-compiler.html
https://github.com/sockeqwe/annotationprocessing101
http://hannesdorfmann.com/annotation-processing/annotationprocessing101
https://www.javacodegeeks.com/2015/09/java-annotation-processors.html
and bonuses
Android related:
https://medium.com/#iammert/annotation-processing-dont-repeat-yourself-generate-your-code-8425e60c6657
https://stablekernel.com/the-10-step-guide-to-annotation-processing-in-android-studio/
https://medium.com/#emmasuzuki/annotation-processor-101-your-first-custom-annotation-a3db9ae48046
http://blog.jensdriller.com/android-annotation-processing-setup-using-gradle/
Kotlin related:
https://blog.jetbrains.com/kotlin/2015/06/better-annotation-processing-supporting-stubs-in-kapt/

How #Aspect with #Component annotation works under the hood

I've been looking for an answer for a while, but no luck so far, thus I'm coming here for some words of wisdom.
I've created an aspect using #Aspect annotation, because I need to #Autowire some singleton dependencies I've decided to annotate this aspect class with #Component and let the Spring to do the magic. It works, however ...
I'm fairly familiar with AOP concept, what's weaving and different flavors of it (cglib vs aspectj) but it's not fully intuitive to me how it works under the hood.
#Component means a given class will be a singleton within a given context, #Aspect means that the content of an aspect class will be somehow weaved into the target class during runtime/compilation - and this target class is not a singleton but prototype for instance. So what I'm ending up with at the end?
Spring AOP does not do compile-time-weaving and does not modify the code of the advised target. Instead it works with proxies that are weaved around the joinpoints. That is why Spring AOP aspects and be used as (singleton) components, have their fields autowired, etc., like any other Spring Proxy.
It is also the reason why Spring AOP aspects only work for public method executions, not field accesses and the like.
The documentation is quite well written and goes into as much (or as little) detail as one might like:
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/aop.html
The book AspectJ in Action's section 2.5 is on the internal working of the weaving step, it is only 2 page but gets the point across well.
Luckily the section is available here.
This is for posterity.

Scenario when we may be needing #Configurable in spring?

I have question about the need of using #configurable. I have gone through the blog that explains how to use #configurable. But the question that comes to my mind is, what can be the scenario when we need to use #configurable. I can think of two scenarios where it can be useful
In a legacy project, when we are already making any bean with new operator and we want to make it spring managed.
In a new project, we want to enforce that even if developer makes the bean with new operator, still it is spring managed.
Otherwise for new beans we can always declare them in applicationContext.xml and I do not see any need to declare them #configurable.
Please let me know if above understanding is correct or if I am missing something.
UPDATE:- Basically as per my understanding configurable is generally used to inject dependency when creating the object with new operator. But why would i be creating the object with new operator when i am using spring
#Configurable annotation is meant for injecting dependencies in domain-driven applications. That means, in such applications, the domain objects interact with each other to perform a certain operation.
Take the following example:
In an invoicing application, the Invoice class provides a constructor to create it, then it has methods to validate, and finally persist it. Now, to persist the invoice, you need a DAO implementation available within the invoice. This is a dependency you would like to be injected or located. With Spring's #Configurable, whenever an invoice is created using the new operator, the appropriate DAO implementation will get injected and can be used for all persist operations.
I had a more realtime scenario where I used #Configurable annotation as described here.

How to add a custom annotation to Spring MVC?

Can anyone explain what I need to do to implement my own annotation that would add functionality to my web requests?
For example:
#Controller
public class MyController {
#RequestMapping("/abc")
#RequiresSomeSpecialHandling
public void handleSecureRequest() {
}
}
Here #RequiresSomeSpecialHandling would be my own annotation that causes some special work to be done before or after the given web request /abc.
I know that on a very high level I would need to write a bean post processor, scan classes for my annotations, and inject custom mvc interceptors when needed. But are there any shortcuts to simplify this task? Especially for the two examples above.
Thanks in advance,
This kind of Annotations, (that add additional functionality when invoking a method) looks like annotations that trigger an AOP Advice.
#see Spring Reference Chapter 7. Aspect Oriented Programming with Spring
The idea is to use the Annotation to trigger the AOP Advice.
like:
#Pointcut("#target(com.example.RequiresAuth)")
Depends on what you want to do as a result of #RequiresSomeSpecialHandling. E.g. do you want it to influence request mappings or the invocation of the method (i.e. resolving method arguments, processing the return value)?
The support for annotated classes in Spring 3.1 became much more customizable. You can browse some examples in this repo.
Also keep in mind that a HandlerInterceptor in Spring 3.1 can cast the handler Object to HandlerMethod, which gives you access to the exact method including its annotations. That may be enough for what you need to do.
If caching is one of your goals, take a look at the #Cacheable annotation (and its siblings #CachePut, #CacheEvict and #Caching), available as of Spring 3.1.

Managing complexity in a dependency-injected app with a large number of beans

I'm working on an Spring application which has a large number of beans - in the hundreds - and it's getting quite cumbersome to use and document.
I'm interested in any experience you have with DI-enabled apps with a large number of beans which would aid maintainability, documentation and general usage.
Although the application is Spring-based with a couple of context files, I'm open to listening about suggestions regarding any DI container and about DI in general as well.
You can use component scan and autowiring features to dramatically decrease the amount of Spring XML configuration.
Example:
<beans>
<!-- Scans service package looking for #Service annotated beans -->
<context:component-scan base-package="my.root.package.service"/>
</beans>
Your service classes must be annotated in order to be automatically scanned:
package my.root.package.service;
#Service("fooService")
public class FooServiceImpl implements FooService{
}
You can also use the #Autowired annotation to tell Spring how to inject the bean dependencies:
package my.root.package.service;
#Service("barService")
public class BarServiceImpl implements BarService{
//Foo service injected by Spring
#Autowired
private FooService fooService;
//...
}
I found the following to be of use:
split your Spring configurations into multiple standalone configurations, and use Spring's import facility to import configuration dependencies (see here, section 3.2.2.1). That way you have a set of configurations that you can combine or disassemble as required, and they are all self-dependent (all the dependencies will be explicit and referenced)
Use an IDE that is Spring-aware, and allows you to navigate through the configurations via point-n-click on beans (references/names, to-and-from source code). Intellij works very well at this (version 7 and beyond, I think). I suspect Eclipse would do something similar.
Revise what you're injecting where. You may want to refactor multiple bean injections into one composite or 'meta' bean, or a larger component. Or you may find that components you once thought you'd need to inject have never changed, or never demanded that injectability (for testing, implementing as strategies etc.)
I used to work with a huge Spring installation, with hundreds (thousands?) of beans. Splitting the configurations up made life a lot more manageable, and simplified testing/creating standalone processes etc. But I think the Intellij Spring integration that came with Intellij made the most difference. Having a Spring-aware IDE is a major timesaver.
As #Wilson Freitas says, use autowiring. I daily work with a system that has few thousand spring managed beans using mostly autowired. But I think the notion of "retaining the overall picture" is slightly misplaced. As a system grows you can't expect to do that in the same way as you did on a smaller system. Using #Autowiring forces you to use stronger typing than xml-based spring, which again means you can use the dependency tracking features of your IDE to navigate in dependencies.
I really think it's suboptimal to think that you need to understand too much of the "full" picture when it comes to the spring configuration. You should be focusing on your code and it's dependencies. Managebility and maintainability are achieved by organizing this code well, naming things well and managing your coupling; all of the stuff that applies even if you're not using spring. Spring shouldn't change much, and with the approval of JSR-330, it may even seem like dependency injection will creep further "under the hood" of the runtime environment.
Our strategy is:
naming conventions, e.g.: fooService, fooDao, fooController;
property setters following these conventions;
autowiring by name (autowire="byName"); we had many problems with autowiring by type, especially on the controller layer

Resources