这两天在写java web项目的时候遇到了个问题,有个Service类每次运行都
会java内存溢出,找了好久也没发现到底哪里错了,最后找到了问题所在:
public class CommunityService{
private CommunityShowService communityShowService = new CommunityShowService();
.
.
.
}
public class CommunityShowService{
private CommunityService communityService = new CommunityService();
.
.
.
}
因为这两个Service有相互的方法需要调用,所以在两个类中都相互实例化了对方,所以在测试的时候就会形成死循环,导致java内存溢出。
我最后的解决办法是写了一个公共的BasicService,在其中把所有的Service都实例化了例如:
public class BasicService {
// 社团
protected static CommunityService communityService = new CommunityService();
// 社团展示
protected static CommunityShowService communityShowService = new CommunityShowService();
// 账号
protected static AccountService accountService = new AccountService();
然后让其他的Service全部继承这个基本的Service,成功解决这个问题