1、springboot項(xiàng)目如何解決循環(huán)依賴(lài)
在生產(chǎn)項(xiàng)目中,可以使用Spring Boot框架來(lái)快速開(kāi)發(fā)Spring應(yīng)用程序。Spring Boot提供了一種方便的方式來(lái)創(chuàng)建獨(dú)立的,基于Spring的應(yīng)用程序,并且有著高度的自動(dòng)化配置和開(kāi)箱即用的特性。
可以使用@Lazy注解來(lái)控制Bean的延遲初始化,同時(shí)可以使用AOP切面編程來(lái)解決循環(huán)依賴(lài)問(wèn)題。具體步驟如下:
1.1、添加@Lazy注解
在需要延遲初始化的Bean上添加@Lazy注解,使其在容器啟動(dòng)時(shí)不會(huì)實(shí)例化。
@Service
@Lazy
public class UserService {
@Autowired
private UserController userController;
// ...
}
1.2、使用@DependsOn,指定加載的順序
在依賴(lài)被初始化前需要注入的Bean上使用@DependsOn注解來(lái)指定Bean之間的依賴(lài)順序。
@RestController
@DependsOn("userService")
public class UserController {
@Autowired
private UserService userService;
// ...
}
1.3、 使用AOP來(lái)實(shí)現(xiàn)Bean的代理
使用Spring AOP來(lái)實(shí)現(xiàn)Bean的代理、懶加載,從而避免循環(huán)依賴(lài)導(dǎo)致的問(wèn)題。其中,當(dāng)被代理的Bean被調(diào)用時(shí),Spring會(huì)先檢查是否已經(jīng)創(chuàng)建了該Bean的代理對(duì)象,如果存在,則直接返回代理對(duì)象,否則再進(jìn)行實(shí)例化并返回。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-501258.html
@Component
@Aspect
public class LazyInitAspect {
private Map<String, Object> singletonObjects = new ConcurrentHashMap<>();
@Around("@annotation(org.springframework.context.annotation.Lazy)")
public Object lazyInit(ProceedingJoinPoint joinPoint) throws Throwable {
String beanName = joinPoint.getSignature().getDeclaringType().getSimpleName();
Object singletonObject = singletonObjects.get(beanName);
if (singletonObject != null) {
return singletonObject;
}
synchronized (this.singletonObjects) {
singletonObject = singletonObjects.get(beanName);
if (singletonObject == null) {
singletonObject = joinPoint.proceed();
singletonObjects.put(beanName, singletonObject);
}
return singletonObject;
}
}
}
以上是基于Spring Boot項(xiàng)目使用@Lazy和AOP解決循環(huán)依賴(lài)問(wèn)題的一種方式。需要注意的是,循環(huán)依賴(lài)會(huì)導(dǎo)致Bean的初始化順序變得復(fù)雜,因此在設(shè)計(jì)應(yīng)用程序時(shí)需要避免過(guò)度的復(fù)雜性。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-501258.html
到了這里,關(guān)于生產(chǎn)項(xiàng)目中基于springboot項(xiàng)目解決循環(huán)依賴(lài)的三種方式的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!