在添加LoggingAspectConfiguration类之前,我的简单应用程序正常工作。源代码如下:(删除了import语句)
这是顶级
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[] { "/" };
}
}
这是组件可以存在的应用程序根类
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());
}
...
}
我开始看到Null指针异常,因为对于loggerCtx依赖注入不起作用。如何解决这个问题?
答案 0 :(得分:0)
Aspect在spring容器外部创建。
不是将LoggingAspectConfiguration创建为组件,而是尝试在ApplicationLogbackConfiguration(这是一个配置类)中创建为bean
在LoggingAspectConfiguration for LoggerContext
中创建一个setter方法@Bean
public LoggingAspectConfiguration getLoggerContext(LoggerContext context)
{
LoggingAspectConfiguration aspect = new LoggingAspectConfiguration();
aspect.setLoggerContext (context)
return aspect;
}
Spring容器按类型autowiresLoggerContext(或者您可以在该方法参数中使用@Autowired注释。)。