目前,Spring 中比较常用的初始化 bean 的方法有:

  • 使用@PostConstruct 注解。
  • 实现 InitializingBean 接口。

1. 使用@PostConstruct 注解

@Service
public class AService {
    @PostConstruct
    public void init() {
        System.out.println("===Initializing===");
    }
}

在需要初始化的方法上添加@PostConstruct 注解。这样,它就具有了初始化的能力

2. 实现 InitializingBean 接口

@Service
public class BService implements InitializingBean {
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("===Initializing===");
    }
}
最后修改:2025 年 08 月 14 日
个人博客