本篇文章為大家展示了Spring中怎么實(shí)現(xiàn)初始化,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。
創(chuàng)新互聯(lián)建站-專業(yè)網(wǎng)站定制、快速模板網(wǎng)站建設(shè)、高性價(jià)比礦區(qū)網(wǎng)站開發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫,直接使用。一站式礦區(qū)網(wǎng)站制作公司更省心,省錢,快速模板網(wǎng)站建設(shè)找我們,業(yè)務(wù)覆蓋礦區(qū)地區(qū)。費(fèi)用合理售后完善,十年實(shí)體公司更值得信賴。
一 指定初始化和銷毀方法
通過@Bean指定init-method和destroy-method;
@Bean(initMethod="init",destroyMethod="detory") public Car car(){ return new Car(); }
二 通過讓Bean實(shí)現(xiàn)InitializingBean(定義初始化邏輯)
@Componentpublic class Cat implements InitializingBean,DisposableBean { public Cat(){ System.out.println("cat constructor..."); } @Override public void destroy() throws Exception { // TODO Auto-generated method stub System.out.println("cat...destroy..."); } @Override public void afterPropertiesSet() throws Exception { // TODO Auto-generated method stub System.out.println("cat...afterPropertiesSet..."); }}
三 可以使用JSR250
@PostConstruct:在bean創(chuàng)建完成并且屬性賦值完成;來執(zhí)行初始化方法@PreDestroy:在容器銷毀bean之前通知我們進(jìn)行清理工作@Componentpublic class Dog implements ApplicationContextAware { //@Autowired private ApplicationContext applicationContext; public Dog(){ System.out.println("dog constructor..."); } //對象創(chuàng)建并賦值之后調(diào)用 @PostConstruct public void init(){ System.out.println("Dog....@PostConstruct..."); } //容器移除對象之前 @PreDestroy public void detory(){ System.out.println("Dog....@PreDestroy..."); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { // TODO Auto-generated method stub this.applicationContext = applicationContext; }}
四 可以使用BeanPostProcessor
/** * 后置處理器:初始化前后進(jìn)行處理工作 * 將后置處理器加入到容器中 * 在bean初始化前后進(jìn)行一些處理工作; * postProcessBeforeInitialization:在初始化之前工作 * postProcessAfterInitialization:在初始化之后工作 */@Componentpublic class MyBeanPostProcessor implements BeanPostProcessor,Ordered { @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { // TODO Auto-generated method stub System.out.println("postProcessBeforeInitialization..."+beanName+"=>"+bean); return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { // TODO Auto-generated method stub System.out.println("postProcessAfterInitialization..."+beanName+"=>"+bean); return bean; } @Override public int getOrder() { return 2; }}
上述內(nèi)容就是Spring中怎么實(shí)現(xiàn)初始化,你們學(xué)到知識或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識儲備,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
分享文章:Spring中怎么實(shí)現(xiàn)初始化
URL地址:http://bm7419.com/article46/gosceg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)頁設(shè)計(jì)公司、網(wǎng)站營銷、品牌網(wǎng)站制作、電子商務(wù)、動態(tài)網(wǎng)站、網(wǎng)站導(dǎo)航
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)