스프링은 빈으로 등록한 클래스의 경우 여러 곳에서 가져다 쓸 수 있게 되는데 빈 등록시 서로 참조하게 등록을 해버리면 순환참조가 일어나게 된다. 이러한 경우 에러가 발생하며 서버가 터지게 되는데 이를 해결하기 위한 여러가지 방법들이 있다.
@Service
public class ServiceA {
@Autowired
private ServiceB serviceB;
public void number1() {
}
}
@Service
public class ServiceB {
@Autowired
private ServiceA serviceA;
public void number2() {
}
}
위의 코드를 막기 위해서는 아래와 같은 방법을 사용하면 된다.
@Service
public class ServiceA {
private ServiceB serviceB;
@Autowired
public void setServiceB(ServiceB serviceB) {
this.serviceB = serviceB;
}
public void doSomething() {
// something
}
}
@Service
public class ServiceB {
private ServiceA serviceA;
@Autowired
public void setServiceA(ServiceA serviceA) {
this.serviceA = serviceA;
}
public void doSomething() {
// something
}
}
@Service
public class ServiceA {
private ObjectProvider<ServiceB> serviceBProvider;
@Autowired
public ServiceA(ObjectProvider<ServiceB> serviceBProvider) {
this.serviceBProvider = serviceBProvider;
}
public void doSomething() {
ServiceB serviceB = serviceBProvider.getObject();
// something
}
}
@Service
public class ServiceB {
private ObjectProvider<ServiceA> serviceAProvider;
@Autowired
public ServiceB(ObjectProvider<ServiceA> serviceAProvider) {
this.serviceAProvider = serviceAProvider;
}
public void doSomething() {
ServiceA serviceA = serviceAProvider.getObject();
// something
}
}
@Service
public class ServiceA {
private ServiceB serviceB;
@Autowired
public ServiceA(ServiceB serviceB) {
this.serviceB = serviceB;
}
public void doSomething() {
// something
}
}
@Service
public class ServiceB {
private ServiceA serviceA;
@Autowired
public ServiceB(ServiceA serviceA) {
this.serviceA = serviceA;
}
public void doSomething() {
// something
}
}