Autowired dependency not injected in Aspect in Spring MVC

前端 未结 2 686
庸人自扰
庸人自扰 2021-02-06 01:19

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

2条回答
  •  说谎
    说谎 (楼主)
    2021-02-06 01:38

    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.

提交回复
热议问题