Using Spring AOP uses underneath aspectj? - spring

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.

Related

Spring AOP logging

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.

Java EE 6 / 7 equivalent for Spring #Configuration

Is there a Java EE 6 / 7 equivalent annotation for Spring's #Configuration?
If the answer is yes then are the equivalents for its surrounding annotations, such as #ComponentScan and #EnableWebMvc?
I did, of course, look for it in Java EE 6 / 7 (I admit I skipped a paragraph here and there), in javadocs (specifically among annotations), in Spring doc, tutorials, blogs, SO and Google.
JEE CDI has also an annotation of creating bean programmatically and exposing them, so it offers bean factories, called producers:
https://dzone.com/articles/cdi-and-the-produces-annotation-for-factory
CDI offers Producer methods (annotated with #Produces) which is the equivalent of #Bean in spring. You can than implement Producers classes that are beans which contain a bunch of producer methods. However, this is by far not as powerful as a spring configuration since as far as I am aware of, there is no possibity to e.g. "import" other configurations (producer classes).
This makes it especially difficult to test CDI applications.
You can either
heavily use mocks to test a single CDI bean to totally avoid injected objects
blow up your test class just to create the instance under test with all dependencies
use testing frameworks like CDI-Unit that creates the beans for you
With 1. Test Driven Development becomes almost impossible and tests have always to be adapted when implementation changes, even if the contract does not change.
With 2. you end up in a lot compiler errors in tests as soon as dependencies between your Beans change
With 3. you need to point your testing framework to the implementation of your beans. Since there exists no Configuration that knows about all beans, the test needs to know about it. Again, if things change your tests will break.
I admit... I don't like CDI ;-P
The javax.servlet.annotation package defines a number of annotations to be used to register Servlet, Filter, and Listener classes as well as do some other configuration, for example, security.
You can also use the ServletContainerInitializer class to configure your ServletContext through Java instead of through the XML deployment descriptor. Spring provides its own implementation of ServletContainerInitializer in which case all you have to do is create a class that implements WebApplicationInitializer and does servlet, filter, and listener registration and leave that class on the classpath.
Examples abound in the javadoc.

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

Combine two maven based projects on two frameworks

I have two maven projects say MvnSpring and MvnGuice.MvnSpring is working on spring and hibernate frame works.
And MvnGuice is working on google guice and mybatis. I need to combine both the features together.
Both are following singleton pattern. I need to get some class of MvnSpring in MvnGuice while coding. So that I created a jar of MvnSpring and put it in .m2 repository and give the dependacy details in MvnGuice. Now I can import classes of MvnSpring in MvnGuice classes.MvnSpring uses spring dependency injection and MvnGuice uses guice dependency injection for object creation. Now in MvnSpring flow is MSserviceImpl(implements MSservice) > MSdaoImpl(implements MSdao). Now I need to call MSService class from MvnGuice. Then at run time it shows error like MSService class is null. Then I made a guice dependency injection for MSService class in MvnGuice. Now the control reaches MSserviceImpl but now MSdao is null at here. Is it possible to start MvnSpring along with MvnGuice. I hope then I can solve the issue.
While Spring and Guice are targeted at the same problem, IoC, they take very different approaches to solve it. They differ both in functionality and in how they are configured, where Spring has bean definitions and Guice uses bindings.
Fortunately they do have common grounds in that they both support JSR-330, a standards specification that defines a set of annotations. This enables you to write your singletons and describe the injections that they need without depending on either Spring or Guice.
This way you can share your singletons between projects irregardless of the framework you use in a particular project. I would not recommend using both Guice and Spring in the same project, except if there's a clearly defined separation between them. For instance you might use Guice for a module that is used by Spring code via a defined API that hides the fact that it internally is based on Guice.
There was already mentioned JSR-330.
For some cases it can be not enough, e.g., you have code:
final String className = config.getProperty(«serviceImpl»);
// Class.forName(name) and check required interface for type safety
final Class<? extends Service> serviceClass = Reflection.classForName(className, Service.class);
final Service service = injector.getInstance(serviceClass);
In different DI environments you are supposed to support both com.guice.inject.Injector.getInstance() and org.springframework.context.ApplicationContext.getBean() implementations.
There is the draft solution sdif4j Simple Dependency Injection Facade.
The idea of this project is to encapsulate different DI frameworks logic with own abstraction to extend default JSR-330 possibilities. Note, there is no public releases yet, but you can find ideas how to solve your problem or make an internal release in a fork.
The general issue, is that your both MvnSpring and MvnGuice projects are supposed to be based on JSR-330 (instead of guice/spring annotations) and org.sdif4j:sdif4j-api (or your own abstraction; only if Injector functionality is required). It is recommended to make guice and spring dependencies optional (to compile but not export) to allow the library clients to choose the DI themselves.
In your MvnCompineGuiceAndSpring you just declare sdif4j-guice or sdif4j-spring dependency (it is similar to slf4j usage) and configure your DI environment. You can find different examples in testing subproject.
Some more notes:
Spring default scope is singleton, Guice - prototype (Spring terminology). So, if you want a prototype bean, you can use:
#org.springframework.context.annotation.Scope("prototype")
#javax.inject.Named
public class TestPrototype {
}
The Spring #Scope annotation should be ignored by guice even if spring does not present in your classpath.
Also you have to declare all your Singleton beans with #javax.inject.Named and #javax.inject.Singleton annotation to support both Spring and Guice, like this:
#javax.inject.Named
#javax.inject.Singleton
public class TestSingleton implements ITestSingleton {
public TestSingleton() {
}
}
As with #Scope annotation, you can use #ImplementedBy(#ProvidedBy) guice annotations on your code (when feasible; be careful with it, in general it is not a good practice), that should be also ignored in Spring DI (in both cases if Spring exists in classpath or not).
Hope, that's clear.

Is it possible to autowire dependencies that are created outside of an ApplicationContext?

I've got an application which uses JAXRS to map Restlet resources using annotations. However, the only entry point I have is essentially defining a list of resource classes in the application configuration. These classes are instantiated by Restlet or JAXRS, so I have no way to put them in my ApplicationContext. Is there a way to have Spring scan the classpath and autowire new instances as necessary? I've already tried using something like below:
#Autowired
private SessionFactory sessionFactory;
Unfortunately, it doesn't really work. Is there a way to do what I'm talking about here?
You can use AspectJ to dependency inject your beans that are created out of your control, or if you create objects using new. You can read more on Springs documentation: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/aop.html#aop-using-aspectj
Essentially what you will do is add #Configurable annotation to the class that you want to be target of injection. You also have to enable it in Spring by having in your Spring xml. Lastly you have to decide between compile time weaving or runtime weaving. Again you can get help from spring documentation.
Loadtime weaving: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/aop.html#aop-aj-ltw
If you use maven you can check this Stackoverflow question for setting up compile time AspectJ: Why doesn't AspectJ compile-time weaving of Spring's #Configurable work?
ApplicationContext.getAutowireCapableBeanFactory().autowireBean(object) will inject all dependencies into the object.

Resources