[英]@Autowire return null after adding Spring AOP
我有spring boot項目,它工作得很好。 但是當我添加spring AOP時,當我使用@Autowired變量時,它會導致我成為nullpointer。
這是我的AOP代碼。
@Autowired
private Service service;
private final org.apache.commons.logging.Log log = LogFactory.getLog(this.getClass());
@Around("execution(* com.kpi.ninja..*.*(..))")
public Object logTimeMethod(ProceedingJoinPoint joinPoint) throws Throwable {
//HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
System.out.println("***********************************************");
StopWatch stopWatch = new StopWatch();
stopWatch.start();
System.out.println("Entering in Method : " + joinPoint.getSignature().getName());
System.out.println("Class Name : " + joinPoint.getSignature().getDeclaringTypeName());
System.out.println("Target class : " + joinPoint.getTarget().getClass().getName());
Object retVal = joinPoint.proceed();
stopWatch.stop();
StringBuffer logMessage = new StringBuffer();
logMessage.append(joinPoint.getTarget().getClass().getName());
logMessage.append(".");
logMessage.append(joinPoint.getSignature().getName());
logMessage.append("(");
// append args
Object[] args = joinPoint.getArgs();
for (int i = 0; i < args.length; i++) {
logMessage.append(args[i]).append(",");
}
if (args.length > 0) {
logMessage.deleteCharAt(logMessage.length() - 1);
}
logMessage.append(")");
logMessage.append(" execution time: ");
logMessage.append(stopWatch.getTotalTimeMillis());
logMessage.append(" ms");
log.info(logMessage.toString());
System.out.println("***********************************************");
return retVal;
}
您正在建議所有方法: @Around("execution(* com.kpi.ninja..*.*(..))")
所以我想Spring AOP排除了MyAspect
類以避免無限遞歸。
盡量縮小范圍@Around
poincut到一個單一的方法先來看看它是否工作。
之后,使用logTimeMethod
注釋從建議中排除logTimeMethod
。
您正在使用nullpointer,因為spring無法初始化Service類,您需要在spring上下文xml中添加服務,因此聲明一個新bean:
<bean id="service" class="[package].Service"></bean>
如果沒有上下文,則應創建一個上下文,並在類聲明中添加批注以設置context.xml的路徑位置:
@ContextConfiguration(locations = { "classpath:/context.xml" })
public class YourClass{
@Autowired
Service service
...methods
}
請確保使用@Autowired的類已用@ Component / @ Service / @ Bean注釋。您發布的代碼不包含初始類定義或spring XML,因此不確定您是否已添加是否添加注釋。
@Component or @Controller or @Bean or @Service/@Repository
Class ACB{
@Autowired
private Service service;
.....
}
通過將一個bean的實例放置到另一個bean的實例的所需字段中來進行自動裝配。 這兩個類都應為bean,即應將它們定義為存在於應用程序上下文中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.