在 spring boot 中,使用 @lazy 延迟注入可以解决循环依赖问题或优化启动性能。具体做法是在构造器、字段或 setter 方法上添加 @lazy 注解,spring 容器会为该 bean 创建一个代理对象进行注入,仅在首次调用其方法时才会触发实际 bean 的初始化。

如何避免循环依赖导致的启动失败
当两个 Bean 互相依赖时,直接注入会导致 AmbiguousException 或启动报错。通过在其中一个类的构造器参数前加上 @Lazy,Spring 会注入一个代理对象,从而打破循环依赖链,使应用正常启动。

package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
@Service
class ServiceA {
private final ServiceB serviceB;
// 使用 @Lazy 注入 ServiceB 的代理
public ServiceA(@Lazy ServiceB serviceB) {
this.serviceB = serviceB;
}
public String doA() {
return "ServiceA executed";
}
public String callB() {
// 只有在这里调用时,ServiceB 才会被真正创建
return serviceB.doB();
}
}
@Service
class ServiceB {
private final ServiceA serviceA;
public ServiceB(ServiceA serviceA) {
this.serviceA = serviceA;
}
public String doB() {
return "ServiceB executed";
}
public String callA() {
return serviceA.doA();
}
}
预期结果:应用成功启动,无循环依赖异常。调用 serviceA.callB() 时,先初始化 ServiceB,再执行 doB 方法。
如何减少非核心 Bean 的启动开销
对于某些不急需使用的重型 Bean(如第三方客户端、大数据量缓存),可以在定义 Bean 的方法或类上使用 @Lazy。这样这些 Bean 不会在应用启动阶段被实例化,而是等到第一次被请求时才加载,从而加快启动速度。

package com.example.demo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
@Configuration
public class AppConfig {
@Bean
@Lazy
public HeavyService heavyService() {
System.out.println("HeavyService is initializing...");
return new HeavyService();
}
}
class HeavyService {
public String process() {
return "Processing data...";
}
}
预期结果:应用启动时控制台不打印 “HeavyService is initializing...”。只有在代码中首次调用 heavyService.process() 后,才会打印该日志并完成初始化。
延迟注入的代理对象有哪些行为特征
通过 @Lazy 注入的 Bean 实际上是一个 CGLIB 或 JDK 动态代理对象。这意味着它不能用于需要原始类型的强转换场景,且如果直接访问 Bean 的属性而非调用方法,可能无法触发初始化。此外,代理对象本身会被放入单例池中,但目标对象的初始化是惰性的。


















