将Spring AOP添加到Spring Boot项目后,以下方面会在我的控制器中的自动装配服务组件上产生NullPointerException:
@Aspect
@Component
@Slf4j
public class LogRequestAspect {
@Around("@annotation(org.springframework.web.bind.annotation.RequestMapping) && execution(public * *(..))")
public Object log(final ProceedingJoinPoint joinPoint) throws Throwable {
final HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
.currentRequestAttributes())
.getRequest();
final Object proceed = joinPoint.proceed();
log.info(
"{} {} from {},{}",
request.getMethod(),
request.getRequestURI(),
request.getRemoteAddr(),
request.getHeader("X-Forwarded-For"));
return proceed;
}
}
示例控制器:
@RestController
public class AController {
@Autowired
AService aService;
@RequestMapping("/doSomething")
private List<Map<String, Object>> doSomething() {
return aService.doSomething();
}
}
示例服务:
@Service
public class AService {
public List<Map<String, Object>> doSomething() {
List<Map<String, Object>> results = new ArrayList<>();
return results;
}
}
配置示例:
@EnableAspectJAutoProxy
@SpringBootApplication
public class Application implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
public void run(String... strings) {
}
}
一旦我删除方面,一切都很完美。知道我在这里缺少什么吗?
默认情况下,Spring AOP使用代理。在这种情况下,正在使用基于类的代理,因为没有实现任何接口。基于类的代理扩展实际类并覆盖应用拦截器/方面的所有方法。
但是,无法在子类中覆盖private
方法,因此将在代理上调用控制器方法而不是代理对象。代理从未注入任何东西,因此aService
字段始终是null
。
要修复方法public
或protected
,以便子类可以覆盖该方法,最终将在代理实例而不是代理上调用该方法。