出现循环依赖的代码:
/**
* @author by mazhen
* @Classname TokenService
* @Date 2020/10/22 10:00
*/
@Component
@Slf4j
public class TokenService {
@Autowired
private AuthenticationService authenticationService;
public void apply() {
authenticationService.method();
}
}
出现了循环依赖,则不能通过@Autowired的方式注入实例,解决方案如下:
/**
* @author by mazhen
* @Classname TokenService
* @Date 2020/10/22 10:00
*/
@Component
@Slf4j
public class TokenService implements BeanFactoryAware {
private BeanFactory beanFactory;
public void apply() {
AuthenticationService authenticationService = beanFactory.getBean(AuthenticationService.class);
authenticationService.method();
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
}
这是我解决循环依赖的一种方式,但不具有普适性,如果有更好的解决方案,请留言评论!