面試刷題30:SpringBean的生命周期?
- 2020 年 4 月 4 日
- 筆記
spring是Java軟體開發的事實標準。
我是李福春,我在準備面試,今天的問題是:springBean的生命周期是怎樣的?
答:spring最基礎的能力是IOC(依賴注入),AOP(面向切面編程),ioc改善了模組之間的耦合問題,
依賴注入的方式:set方法,構造方法,成員變數+ @Autowire
;Bean的管理是IOC的主要功能。
bean的生命周期完全由spring容器管理,從屬性設置到各種依賴關係的注入,簡化了開發人員對bean的生命周期認知;
Spring的容器中Bean生命周期如下:
對象創建
1,從xml配置的Bean,@Bean註解,或者Java程式碼BeanDefinitionBuilder
中讀取Bean的定義,實例化Bean對象;
2,設置Bean的屬性;
3,注入Aware的依賴(BeanNameAware,BeanFactoryAware,ApplicationContextAware);
4, 執行通用的方法前置處理,方法: BeanPostProcessor.postProcessorBeforeInitialization()
5, 執行 InitalizingBean.afterPropertiesSet()
方法
6,執行Bean自定義的初始化方法init,或者 @PostConstruct
標註的方法;
7,執行方法BeanPostProcessor.postProcessorAfterInitialization()
8, 創建對象完畢;
對象銷毀
9, 執行 DisposableBean.destory()
方法;
10,執行自定義的destory方法或者 @PreDestory
標註的方法;
11,銷毀對象完畢
下面擴展一下spring的bean關聯面試問題。
Bean的作用域
面向切面編程
aop:為了java的應用更好的模組化,解決程式中的事務,安全,日誌等問題;
使用java的動態代理(介面代理)或者CGlib(擴展代理類)實現。
主要元素如下圖:
Aspect: 定義切面 , Advice定義增強,增強的類型見上圖;
pointcut: 切點,即切入哪些類的哪些方法;
spring應用中使用AOP的實例程式碼:
import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Service; import java.lang.reflect.Method /** * 服務層AOP */ @Aspect @Service @Order(0) @Slf4j public class ServiceInterceptor { @Pointcut("execution(public * com.xxx.ihs.yyy.admin.manager..*.*(..))") public void pointcut() { } private String serviceName() { return "xxxrest"; } @Around("pointcut()") public Object around(ProceedingJoinPoint pjp) throws Throwable { Method method = ((MethodSignature) pjp.getSignature()).getMethod(); final String methodName = method.getDeclaringClass().getCanonicalName().concat(".").concat(method.getName()); Object[] args = pjp.getArgs(); Object returnObj = null; try { returnObj = pjp.proceed(); } catch (Exception ex) { String message = String.format("[%s]服務發生系統錯誤:%s", this.serviceName(), ex.getMessage()); log.error("{}, method:{},args:{}", message, methodName, JsonUtils.toJson(args), ex); throw ex; } return returnObj; } }
小結
本篇回答了spring的ioc容器的Bean生命周期的過程。
然後簡單的說明了一下Bean的作用範圍;
最後說到了AOP,簡要的介紹了使用的場景,切入流程以及一個使用實例。
原創不易,點贊關注支援一下吧!轉載請註明出處,讓我們互通有無,共同進步,歡迎溝通交流。
我會持續分享Java軟體編程知識和程式設計師發展職業之路,歡迎關注,我整理了這些年編程學習的各種資源,關注公眾號『李福春持續輸出』,發送’學習資料’分享給你!