[英]Dependency Injection to Aspect method in Spring Boot Test (JUnit)
当我不使用我的CronLogService
时,我的 Aspect 方法有效,但如果我注入这个我有这个错误:
No qualifying bean of type 'com.app.service.CronLogService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
我的方面方法:
@Aspect
@Component
@RequiredArgsConstructor
@EnableAspectJAutoProxy
@Slf4j
public class CronLoggerAspect {
private final CronLogService cronLogService;
@Around("@annotation(CronLogger)")
public Object trace(ProceedingJoinPoint joinPoint) throws Throwable {
String name = MethodSignature.class.cast(joinPoint.getSignature()).getMethod().getAnnotation(CronLogger.class)
.name();
log.debug("start CronLogger for {}", name);
....
}
}
我的服务:
@Service
@Transactional
@RequiredArgsConstructor
@Slf4j
public class CronLogServiceImpl implements CronLogService {
private final CronLogRepository cronLogRepository;
@Override
public CronLog create(CronLog cronLog) {
return cronLogRepository.save(cronLog);
}
...
}
我只在我的 JUnit 测试中出现此错误(我的 Springboot 应用程序工作:!):
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = {TaskService.class, CronLoggerAspect.class, CronLogService.class, CronLogRepository.class})
public class TaskTest {
@Autowired
private TaskService taskService;
@Test
void testCronLoggerSuccess() throws CronException {
taskService.testCronLogger("test Success");
}
}
我的测试服务:
@Service
@RequiredArgsConstructor
@Slf4j
public class TaskService {
@CronLogger(name = "unit test")
public void testCronLogger(String param) throws CronException {
log.info("testCronLogger for {}", param);
...
}
}
我的CronLogRepository
public interface CronLogRepository extends JpaRepository<CronLog, String> {
}
编辑:
//@RequiredArgsConstructor
@Slf4j
public class CronLogServiceImpl implements CronLogService {
@Autowired
private CronLogRepository cronLogRepository;
测试:没有“com.app.repository.CronLogRepository”类型的合格 bean 可用:预计至少有 1 个有资格作为自动装配候选者的 bean。 依赖注解:{@org.springframework.beans.factory.annotation.Autowired(required=true)}
弹簧靴:好的
@RequiredArgsConstructor
@Slf4j
public class CronLogServiceImpl implements CronLogService {
private CronLogRepository cronLogRepository;
测试:没有 spring 错误,但cronLogRepository
是 null。 所以cronLogRepository.save
返回一个java.lang.NullPointerException
springboot: CronLogServiceImpl.create 上的 java.lang.NullPointerException: CronLogServiceImpl.create
@SpringBootTest(类 = {TaskService.class,CronLoggerAspect.class,CronLogService.class,CronLogRepository.class})
可能错误在这一行,尝试用@SpringBootTest
替换它,如果它有效,那么错误在上下文配置中。 我认为,您需要将CronLogServiceImpl
添加到要添加到上下文的类列表中。
这能解决你的问题吗? 在评论中告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.