I am not able to @Autowire
the Service Layer Instance in Aspect. In Aspect the reference to the @Autowired
bean is NULL and it throws NullPointer
See this piece of the documentation:
7.8.3 Configuring AspectJ aspects using Spring IoC
When using AspectJ aspects with Spring applications, it is natural to both want and expect to be able to configure such aspects using Spring. The AspectJ runtime itself is responsible for aspect creation, and the means of configuring the AspectJ created aspects via Spring depends on the AspectJ instantiation model (the 'per-xxx' clause) used by the aspect.
The majority of AspectJ aspects are singleton aspects. Configuration of these aspects is very easy: simply create a bean definition referencing the aspect type as normal, and include the bean attribute 'factory-method="aspectOf"'. This ensures that Spring obtains the aspect instance by asking AspectJ for it rather than trying to create an instance itself. For example:
<bean id="profiler" class="com.xyz.profiler.Profiler"
factory-method="aspectOf" />
For anyone looking for a java based bean configuration, Using java reflections I could archive the same
@Bean
public ExceptionAspectHandler exceptionAspectHandler(){
try
{
//noinspection JavaReflectionMemberAccess
Method method = ExceptionAspectHandler.class.getMethod("aspectOf" );
return (ExceptionAspectHandler) method.invoke(null);
}
catch( IllegalAccessException | InvocationTargetException | NoSuchMethodException e )
{
logger.log( Level.SEVERE, "Error creating bean : ", e );
}
return null;
}
Since the aspectOf()
method is not available during compile time we cannot create the bean by just calling the method. That is why XML configuration is able to handle it.
Alternatively simpler approach
@Bean
public ExceptionAspectHandler exceptionAspectHandler()
{
return Aspects.aspectOf( ExceptionAspectHandler.class );
}
This also does work.