I read here:
/@dulanjayasandaruwan1998/spring-doesnt-recommend-autowired-anymore-05fc05309dad
Basically can removed the @Autowired
and replaced it to private final
like this:
@Service
@RequiredArgsConstructor
public class MyService {
private final MyRepository myRepository;
}
However, I try to use it for repo, it is working but it is not working for service. It have error like this:
Action:
Despite circular references being allowed, the dependency cycle between beans could not be broken. Update your application to remove the dependency cycle.
Here is the concept that I want to do:
@Service
@RequiredArgsConstructor
public class AnotherService {
private final MyService myService;
}
@Service
@RequiredArgsConstructor
public class MyService {
private final AnotherService anotherService;
}
Is there any way that I could make it work while removing the @Autowired
.
I read here:
https://medium/@dulanjayasandaruwan1998/spring-doesnt-recommend-autowired-anymore-05fc05309dad
Basically can removed the @Autowired
and replaced it to private final
like this:
@Service
@RequiredArgsConstructor
public class MyService {
private final MyRepository myRepository;
}
However, I try to use it for repo, it is working but it is not working for service. It have error like this:
Action:
Despite circular references being allowed, the dependency cycle between beans could not be broken. Update your application to remove the dependency cycle.
Here is the concept that I want to do:
@Service
@RequiredArgsConstructor
public class AnotherService {
private final MyService myService;
}
@Service
@RequiredArgsConstructor
public class MyService {
private final AnotherService anotherService;
}
Is there any way that I could make it work while removing the @Autowired
.
2 Answers
Reset to default 0You can use @Lazy
annotation to inject the bean lazily which avoids circular dependency.
Recommended in constructor injection.
Adding spring.main.allow-circular-references=true
or using @Lazy
should have worked. If not you could inject ApplicationContext
and fetch your service using the reference of ApplicationContext
@Service
@RequiredArgsConstructor
public class AnotherService {
private final ApplicationContext context;
public void yourMenthos() {
MyService svc = context.getBean(MyService.class);
...
}
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745104882a4611497.html
MyService
needsAnotherService
, whileAnotherService
needsMyService
. They depend an each other. Remove the circulair dependency is the proper way forward. – M. Deinum Commented Mar 3 at 8:24