phildeg31
phildeg31

Reputation: 269

Circular reference issue with abstract class

After an upgrade of one of our app in Spring Boot v2.7.6, I have an issue about a circular reference.

I have an abstract class like this:

public abstract class AbstractTransactionalService<Request, Response, Exception> {

    @Autowired
    private ApplicationContext applicationContext;

    private AbstractTransactionalService<Request, Response, Exception> me;

    @SuppressWarnings("unchecked")
    @PostConstruct
    public void init() {
        me = applicationContext.getBean(this.getClass());
    }

    public Response performService(final Request request, final Class<Exception> exceptionClass)
            throws Exception {
        try {
            final Response response = this.me.perform(request);
            return response;
        } catch (final Exception e) {
            ...
        }
    }

    public abstract Response perform(Request request) throws Exception;
}

A service 2 extends AbstractTransactionalService and implements the perform() method. This service 2 is used in an other service 1 (injected with @Autowired and a call to performService() method is done).

I have a circular reference issue with the service that calls the service 2 extending the abstract class at server startup. When the service 1 does @Autowired for the service 2 extending the abstract class, the service 2 extending the abstract class is in creation. It seems that when the call to ApplicationContext.getBean() is done in the abstract class, it causes the circular reference error because he current bean is in creation.

I do not know how to solve it. Do you have an idea please?

Upvotes: 0

Views: 156

Answers (1)

dimirsen Z
dimirsen Z

Reputation: 891

I faced a similar issue and fixed it as follows. Created ServiceManager as a bean, autowired all the services involved in cycle(s) within it. And then retrieved the services via getters from the serviceManager. The serviceManager itself is to be retrieved via @Autowire where it is needed.

Upvotes: 0

Related Questions