目前,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===");
}
}