文章目錄
- bean的生命周期
- 1. Bean定義階段
- 2. Bean實例化階段
- 3. 屬性賦值階段
- 4. 初始化階段
- 5. 使用階段
- 6. 銷毀階段
bean的生命周期
在Spring Boot中,Bean的生命周期包括定義、實例化、屬性賦值、初始化、使用和銷毀等階段。下面我將詳細解釋這些階段,并提供相應的代碼示例。
1. Bean定義階段
Bean的定義通常通過注解(如@Component
、@Service
、@Repository
、@Controller
等)、XML配置或Java配置類(@Configuration
)來實現。
代碼示例(使用注解定義Bean):
@Service
public class MyService {// ...
}
2. Bean實例化階段
在這一階段,Spring容器會根據Bean的定義創建Bean的實例。實例化方式包括構造器實例化、靜態工廠方法實例化和實例工廠方法實例化。
代碼示例(構造器實例化):
// Spring容器會通過無參構造器創建MyService的實例
@Service
public class MyService {public MyService() {// 構造器邏輯}// ...
}
3. 屬性賦值階段
在Bean實例化之后,Spring容器會將Bean定義中聲明的依賴注入到Bean實例的屬性中。
代碼示例(使用@Autowired
注入依賴):
@Service
public class MyService {private final MyRepository myRepository;@Autowiredpublic MyService(MyRepository myRepository) {this.myRepository = myRepository;}// ...
}
4. 初始化階段
在Bean準備好被使用之前,Spring容器會執行一系列的初始化邏輯。這包括Aware接口回調、BeanPostProcessor前置處理、初始化方法和BeanPostProcessor后置處理。
代碼示例(實現InitializingBean
接口):
import org.springframework.beans.factory.InitializingBean;@Service
public class MyService implements InitializingBean {@Overridepublic void afterPropertiesSet() throws Exception {// 初始化邏輯}// ...
}
或者使用@PostConstruct
注解:
import javax.annotation.PostConstruct;@Service
public class MyService {@PostConstructpublic void init() {// 初始化邏輯}// ...
}
5. 使用階段
在Bean完全初始化后,它就可以被應用程序使用了。開發者可以通過依賴注入或ApplicationContext
來獲取Bean的實例。
代碼示例(使用ApplicationContext
獲取Bean):
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class Main {public static void main(String[] args) {ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);MyService myService = context.getBean(MyService.class);// 使用myService}
}
6. 銷毀階段
當Bean不再需要時,Spring容器會負責銷毀它。銷毀過程包括執行銷毀回調接口或銷毀方法。
代碼示例(實現DisposableBean
接口):
import org.springframework.beans.factory.DisposableBean;@Service
public class MyService implements DisposableBean {@Overridepublic void destroy() throws Exception {// 銷毀邏輯}// ...
}
或者在配置文件中指定destroy-method
:
<bean id="myService" class="com.example.MyService" destroy-method="cleanup"/>
請注意,對于Web應用程序,Spring容器通常會在Web服務器關閉時自動銷毀所有的Bean。而對于非Web應用程序,你可能需要手動關閉ApplicationContext
來觸發Bean的銷毀過程。
希望這些代碼示例能幫助你更好地理解Spring Boot中Bean的生命周期。