2017-08-17 46 views
0

我的简单应用程序在添加LoggingAspectConfiguration类之前工作正常。源代码如下:(除去导入语句)@ @Aspect中的自动注入依赖注入LoggerContext为null

这是顶级

package com.rsa.tools.springmvc.configuration; 

public class ApplicationInitialization extends AbstractAnnotationConfigDispatcherServletInitializer { 
    @Override 
    protected Class<?>[] getRootConfigClasses() { 
    return new Class[] { ApplicationRootClassConfiguration.class }; 
    } 

    @Override 
    protected Class<?>[] getServletConfigClasses() { 
    return new Class[] { ApplicationWebConfiguration.class }; 
    } 

    @Override 
    protected String[] getServletMappings() { 
    return new String[] { "/" }; 
    } 
} 

这是应用程序的根类,其中componentscan呈现

package com.rsa.tools.springmvc.configuration.backend; 

@Configuration 
@EnableAspectJAutoProxy 
@ComponentScan(basePackages={"com.rsa.tools.springmvc.configuration.general", "com.rsa.tools.springmvc.configuration.backend", "com.rsa.tools.springmvc.dao", "com.rsa.tools.springmvc.service"}) 
public class ApplicationRootClassConfiguration { 
} 

的logback配置

package com.rsa.tools.springmvc.configuration.general; 

@Configuration 
public class ApplicationLogbackConfiguration { 
    @Bean 
    public LoggerContext getLoggerContext() { ... } 
} 

直到这里它工作正常。

后,我增加了以下类:

package com.rsa.tools.springmvc.configuration.general; 

@Aspect 
@Component 
public class LoggingAspectConfiguration { 
    @Autowired 
    LoggerContext loggerCtx; 

    @Pointcut("execution(* *.*(..))") 
    protected void loggingOperation() {} 

    @Before("loggingOperation()") 
    @Order(1) 
    public void logJoinPoint(JoinPoint joinPoint) { 
    Logger logger = loggerCtx.getLogger(this.getClass()); 
    logger.trace("Join point kind : " + joinPoint.getKind()); 
    logger.info("Signature declaring type : "+ joinPoint.getSignature().getDeclaringTypeName()); 
    logger.info("Signature name : " + joinPoint.getSignature().getName()); 
    logger.info("Arguments : " + Arrays.toString(joinPoint.getArgs())); 
    logger.info("Target class : "+ joinPoint.getTarget().getClass().getName()); 
    logger.info("This class : " + joinPoint.getThis().getClass().getName()); 
    } 
    ... 
} 

我开始看到空指针异常,因为loggerCtx依赖注入没有工作。如何解决这个问题?

+0

'@ Order'是Spring的注释吗?你为什么在'logJoinPoint'方法上使用它? –

+0

我删除它,仍然是同样的问题。 –

回答

0

在春天容器外面创建方面。

不用创建LoggingAspectConfiguration的作为组分尝试创建如ApplicationLogbackConfiguration豆(这是一个配置类)

创建内部LoggingAspectConfiguration setter方法用于LoggerContext

@Bean 
public LoggingAspectConfiguration getLoggerContext(LoggerContext context) 
{ 
LoggingAspectConfiguration aspect = new LoggingAspectConfiguration(); 
aspect.setLoggerContext (context) 
return aspect; 
} 

Spring容器autowiresLoggerContext按类型(或者您可以在该方法参数中使用@Autowired注释。)。

+0

这是什么“a”?如何在ApplicationLogbackConfiguration中将它创建为@Bean来指定Aspect?你说setter方法。代码示例是用于getter方法的。我在这里错过了一些东西。 –

+0

错字更正。正如我所说的方面是在容器外,并且loggercontext是一个spring bean,这让容器知道bean是加载它的一个方面,因此它也设置了loggercontext。 – surya