Spring Bean的生命周期:一场从“出生”到“归零”的奇妙旅程

184 阅读3分钟

我是洋哥,一个拥有6年经验的程序员,Litchi开源组织发起人。

今天我要带你们踏上一段奇幻之旅,探索Spring框架中Bean的生命周期。在这个旅程中,我们将看到Spring Bean如何从无到有,经历种种奇遇,最终成为我们应用程序中不可或缺的一部分。

一场生命的奇迹

在Spring框架中,Bean的生命周期是一个精心设计的流程,确保Bean在创建、使用和销毁过程中能够正确地初始化、配置和销毁。下面我们将通过代码来解析这个流程。

萌芽——Bean的实例化

当Spring容器启动时,它会根据配置文件或注解来创建Bean的实例。

@Configuration  
public class AppConfig {  
  
    @Bean  
    public MyService myService() {  
        return new MyServiceImpl();  
    }  
}

在上面的代码中,AppConfig 是一个配置类,使用@Bean注解来定义myService方法,该方法返回MyServiceImpl的实例。当Spring容器启动时,它会调用这个方法,实例化MyServiceImpl类,并作为一个Bean管理。

生长——依赖注入

在实例化之后,Spring容器会负责为Bean的属性注入依赖。

@Service  
public class MyServiceImpl implements MyService {  
  
    private final AnotherService anotherService;  
  
    @Autowired  
    public MyServiceImpl(AnotherService anotherService) {  
        this.anotherService = anotherService;  
    }  
}

在MyServiceImpl的构造函数中,AnotherService类型的anotherService属性被@Autowired注解标记,表明这是一个需要Spring容器注入的依赖。Spring容器会负责创建AnotherService的实例,并将其注入到MyServiceImpl中。

开花——初始化

Bean的初始化可以通过实现InitializingBean接口或使用@PostConstruct注解来完成。

@Service  
public class MyServiceImpl implements MyService, InitializingBean {  
  
    // ... 依赖注入的代码 ...  
  
    @Override  
    public void afterPropertiesSet() throws Exception {  
        // 初始化逻辑  
    }  
  
    @PostConstruct  
    public void init() {  
        // 另一种初始化逻辑  
    }  
}

afterPropertiesSet方法是InitializingBean接口的方法,它会在依赖注入完成后被调用。而@PostConstruct注解的方法会在依赖注入之后、Bean被使用之前自动调用。

结果——使用

完成初始化后,Bean就可以被应用程序使用了。

@RestController  
public class MyController {  
  
    private final MyService myService;  
  
    @Autowired  
    public MyController(MyService myService) {  
        this.myService = myService;  
    }  
  
    @GetMapping("/hello")  
    public String hello() {  
        return myService.doSomething();  
    }  
}

在上面的MyController中,我们注入了MyService的实例,并在hello方法中使用它。当HTTP GET请求发送到/hello时,Spring MVC会调用hello方法,从而间接使用MyService。

落叶归根——销毁

当Bean不再被需要时,它的生命周期也将走向终点。

@Service  
public class MyServiceImpl implements MyService, DisposableBean {  
  
    // ... 依赖注入和初始化的代码 ...  
  
    @Override  
    public void destroy() throws Exception {  
        // 销毁逻辑  
    }  
}

DisposableBean接口有一个destroy方法,当Bean即将被销毁时,Spring容器会调用这个方法。此外,你也可以使用@PreDestroy注解来标记一个方法,该方法将在Bean销毁之前被调用。

结语:生命的轮回

Spring Bean的生命周期就像是一场从“出生”到“归零”的奇妙旅程。从实例化到依赖注入,再到初始化和使用,最终到销毁,每一个阶段都充满了生命的活力和魅力。通过实现特定的接口或使用注解,我们可以参与到这个流程中,为Bean提供自定义的初始化、销毁逻辑等。了解和掌握Spring Bean的生命周期,我们可以更好地利用Spring框架来构建高效、稳定的应用程序。


欢迎关注我的公众号“程序员洋哥”,原创技术文章第一时间推送。

image.png