while the pointcut be apply to bean ctor and all get/set property methods? - spring

I have a Spring AOP pointcut execution(* someService.*(..)).
Will this pointcut match constructor and bean get/set property methods?
THIS is not my intention, and also maybe this behaviour will hurt performance.
I just want to advise REAL service methods, such us getUserByID etc.
How do I exclude those methods (get/set/constructor)?

That pointcut will match public methods in Spring AOP. So getters and setters, but not constructors.
The Spring reference for this is here. Section 8.2.3, look for "even constructors".
A clean way to only reference a group of methods is to apply the pointcut to an interface implemented by your service, instead of the service itself. This assumes your interface only contains business methods you want to advise.

in case it's a third party library and you don't want to use a marker interface for some reason, you can always base yourself on naming conventions of the methods. For example this applies the aspect to getters only:
execution(* someService.get*(..))
this expression applies the aspect to both getters and setters:
execution(* someService.get*(..)) && execution(* someService.set*(..))

Related

Incorrect usage of Stereotypes in Spring and what do they actually do behind the scenes

Can the specialised variants of Spring's #Component be inappropriately used? i.e. if I call my service class #Repository instead of #Service or the reverse.
Is there any safeguards against such inappropriate use or is it just a recommendation that they be used correctly as per context without any enforcement from Spring?
Could some one please let me know what exactly happens with each Stereotype?I read the javadocs and don't fully understand what specialised set of features does each of Spring Stereotype offers
Yes, you can annotate any class with #Repository or #Service, and both of them will behave the same but here comes the interesting point from documentation:
Therefore, you can annotate your component classes with #Component, but by annotating them with #Repository, #Service, or #Controller instead, your classes are more properly suited for processing by tools or associating with aspects. For example, these stereotype annotations make ideal targets for pointcuts.
Thus, if you are choosing between using #Component or #Service for
your service layer, #Service is clearly the better choice. Similarly,
as stated above, #Repository is already supported as a marker for
automatic exception translation in your persistence layer.
Here you can see two important things being discussed Ideal target for pointcuts in the first para and 2nd one as automatic exception translation
Clearly, 1st one is understandable if you are aware of AOP and second one is one beautiful thing about these annotations. Lets see the docs what does automatic exception translation mean:
Common data access exceptions. Spring can wrap exceptions from your O/R mapping tool of choice, converting them from proprietary (potentially checked) exceptions to a common runtime DataAccessException hierarchy. This allows you to handle most persistence exceptions, which are non-recoverable, only in the appropriate layers, without annoying boilerplate catches/throws, and exception declarations. You can still trap and handle exceptions anywhere you need to. Remember that JDBC exceptions (including DB specific dialects) are also converted to the same hierarchy, meaning that you can perform some operations with JDBC within a consistent programming model.
So basically, they are same, but they differ a little when you dig deep. Hope you got it.
for example, if we annotate all the classes with #Service annotation, all of these classes will be registered in the container but how things will differ. See, if you annotate some class with #Repository annotation, the postprocessor automatically looks for all exception translators (implementations of the PersistenceExceptionTranslator interface) and advises all beans marked with the #Repository annotation so that the discovered translators can intercept and apply the appropriate translation on the thrown exceptions.
So, again, it is all about some sort of exception handling. Now, if you annotate the class with #Service annotation rather than #Repository annotation, the required translators will not get discovered.
Now regarding #Service annotation. This annotation doesn't bring more to the table than #Component. They are same, the only difference is #Service annotation is a specialization of #Component , and the only specialization it adds according to the docs is
This annotation is a general-purpose stereotype and individual teams may narrow their semantics and use as appropriate.
Hence, #Service just adds more understanding than #Component.
So, at the end, we came to know that all are nearly same with slight differences where #Repository annotations has some more benefits in case of DAO class.

Spring Weaving: #Configurable objects do not get woven correctly if used as a Parameter inside Methods of Autoproxies

Please consider following situation with spring 4.0.7
For Eclipselink, we use a load-time-weaver. So we wanted to experiment with Springs #Configurable annotation using #EnableSpringConfigured with #EnableLoadTimeWeaving at the same time.
This is fully functional, and Spring-Beans are injected perfectly into POJOs during construction. This functionality is helpful for us, because we want to keep some code regarding validation of these POJOs inside these and not somewhere else in a Bean.
SOme of our Spring Context contains Beans that do not implement any interface, because they are local to some package and used only there. Lets say, FooLogicBean is one of them. If this is to be injected into another Bean, and some Spring-AOP-Aspect (not-aspectj) like some performance measurement aspect is in the execution path, Spring will create a CGLIB autoproxy for the FooLogicBean and inject that. This is fully functional and works perfectly too.
Problems arise, when we want to actually use a POJO that is annotated with #Configurable as a parameter in a method of FooLogicBean (like fooLogicBean.doValidate(myPojo); ), respectively a CGLIB Proxy. In this case, some non-trivial magic stops that POJO from being woven thru aspectj (AnnotationBeanConfigurerAspect from spring-aspects). It is even never woven anywhere in the code regardless of calling the aforementioned doValidate() Method.
If we create that POJO inside FooLogicBean, but dont use it as a method Parameter, it gets woven again due to #Configurable.
Without knowing the Autoproxy creation code, we assume some fancy marking routine from hindering a class from being detected by aspectj, if that class was already used in spring-aop. use in this case means Access.
Did anyone experiment with such obscure constellation and knows a solution for that?
Thanks in advance!
Proxies are created by subclassing, i.e. when you create a proxy of an annotated class Foo:
class Foo {
#Bar
void bar() { }
}
the proxy is created by implementing a class
class Foo$Proxy extends Foo {
#Override
void bar() {
// Proxy logic
}
// Overridden methods of Object
}
This makes the Foo$Proxy class a valid Liskov substitute for Foo. However, normal override semantics apply, i.e. non-inherited annotations such as #Bar are not longer present for the overridden methods. Once another annotation-based API processes your beans, all annotations have disappeared which leads to your outcome. This is true for all kinds of annotations. Those on types, methods and method parameters.
But is it avoidable? It most certainly is by using a proxy generator that was written recently and is built with knowledge of what annotations are, something that is not true for cglib which was first shipped in the early days of the Java virtual machine. However, as long as Spring does not move away from cglib, you will have to live with today's limitations.

Is the following pointcut valid?

I came across the following Spring AOP pointcut in a tutorial:
execution(public * * (..))
it was said that it would cause the execution of all public methods. Is that correct? AFAIK we can only intercept public methods, and that public keyword there is even illegal.
In addition to #Mario's answer, the spring docs on AOP say the following (emphasis mine):
Note 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.
In addition, the pointcut grammer is as follows:
execution(modifiers-pattern? ret-type-pattern declaring-type-pattern?
name-pattern(param-pattern) throws-pattern?)
Wherby the modifier-pattern would be public,protected etc but is optional...
Yes, it seems to be a valid pointcut, and it does exactly what he says.
In addition, it is worth to note that replacing the "public" keyword with "protected" is perfectly legal and it still works! Strangely it works also with "private" methods...
(Tested with Spring 3.1.2 + AspectJ 1.6.9)
As far as I know, CGLib proxies can be used to proxy protected methods, however they are effective only if they are invoked from a different object instance. So technically, it should be possible to advice protected methods exactly in the same way as public ones.
(As reported by #beny23 advicing protected/private methods does not work with Spring AOP proxy implementation, but only with Spring driven AspectJ weaving)
pointcut: designator(modifier returnType package.type.method(params))
in your case
execution(public * * (..))
would execute for all public methods with ANY return type in the project dir with 0 to many parameters

what exactly does the #with annotation do? (Play Framework)

I don't quite understand what the #with annotation does.
in the Play framework site, it is written :
we can annotate the controllers using the #With annotation to tell
Play to invoke the corresponding interceptors
is it the same as inheritance ? will it invoke #before of the given class parameter ? what exactly does it do ?
The best way I can describe it, is that it kind of gives you multiple inheritance at your controller level for your interceptors. Interceptors being the #Before, #After annotations.
You could therefore
define a controller that dealt with your secure area #Before annotations
define a controller that dealt with injecting your static data for shared actions using #Before
you could then define a controller or controllers that contained all your actions, and use the #With annotation to make use of the two controllers described above. It means you can separate your code out cleanly, and not have to rely on inheritance to execute the #Before annotations.
Suppose you have 2 controllers:
A has #Before or other controller action injection annotations,
B get annotated with #With(A.class)
All those injection actions defined in A will be effective when calling B's action methods.
It's kind of inheritance. However with inheritance you can extend at most one class. But you can do #With({A.class, Z.class, ...})

Aspect pointcut to match Annotation property

I'm trying to use Spring AOP with AspectJ support to weave methods with a certain annotation. I know it's easy to do so by using a pointcut #annotation(classname)
But I need to create weavers based on properties of the annotation. The annotation in question is Spring's #RequestMapping, and I need to check the method property of it.
I know I could access it inside the body of the advice, but what I really would like is to create one advice per matched annotation.
Is this possible?
There doesn't seem to be a way to do it, but you can check the parameters of the annotation immediately on entry and immediately pass it on if they're not satisfied.
#Around("execution(public * *(..)) && #annotation(reqMap)")
public Object myMethod(ProceedingJoinPoint pjp, RequestMapping reqMap)
throws Throwable {
if (notRightPropertyValue(reqMap))
return pjp.proceed();
// Do your stuff here
}
If this is too inelegant, consider inventing an extra annotation to mark just the methods that you're really interested in.

Resources