今天debug代码时,遇到一个坑
public interface LoopService {
void testLoop();
void testInnerLoop();
}
@Service
public class DefaultLoopService implements LoopService {
private static final Logger log = LoggerFactory.getLogger(DefaultLoopService.class);
@Override
public void testLoop() {
log.info("DefaultLoopService");
}
@Override
public void testInnerLoop() {
log.info("DefaultLoopService--testInnerLoop");
}
}
@Service
@Primary
public class UsingLoopService implements LoopService {
private static final Logger log = LoggerFactory.getLogger(UsingLoopService.class);
@Autowired
private LoopService loopService;
@Override
public void testLoop() {
log.info("UsingLoopService");
loopService.testInnerLoop();
}
@Override
public void testInnerLoop() {
log.info("UsingLoopService--testInnerLoop");
}
}
@RestController
public class LoopController {
@Autowired
private LoopService loopService;
@GetMapping("/testLoop")
public void testLoop() {
loopService.testLoop();
}
}
当我请求http://localhost:8080/testLoop时,
期望打印
UsingLoopService : UsingLoopService
UsingLoopService : UsingLoopService–testInnerLoop
但实际却打印
UsingLoopService : UsingLoopService
UsingLoopService : DefaultLoopService–testInnerLoop
给UsingLoopService命名
@Service("usingLoopService")
@Primary
public class UsingLoopService implements LoopService {
private static final Logger log = LoggerFactory.getLogger(UsingLoopService.class);
@Autowired
@Qualifier("usingLoopService")
private LoopService loopService;
@Override
public void testLoop() {
log.info("UsingLoopService");
loopService.testInnerLoop();
}
@Override
public void testInnerLoop() {
log.info("UsingLoopService--testInnerLoop");
}
}
这时打印符合预期
UsingLoopService : UsingLoopService
UsingLoopService : UsingLoopService–testInnerLoop
哪位大神有更好的解决方案,不防写在下面评论区 ↓ downarrow ↓



