spring6:bean的生命始末方法
生活随笔
收集整理的這篇文章主要介紹了
spring6:bean的生命始末方法
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
?
package com.atChina2.service;public class SomeServiceImpl implements SomeService {public SomeServiceImpl(){System.out.println("SomeServiceImpl...無參構(gòu)造函數(shù)..");}@Overridepublic void doSome() {System.out.println("doSome業(yè)務(wù)方法...");}// 定義bean的生命始末方法,自定義方法參與到spring創(chuàng)建和銷毀對(duì)象的過程中。// 初始化方法public void startUp(){System.out.println("bean的初始化方法,可以完成構(gòu)造方法的功能,給屬性賦值,初始化其他對(duì)象");}// bean銷毀之前執(zhí)行的方法public void endDown(){System.out.println("bean對(duì)象銷毀之前執(zhí)行的方法,清楚對(duì)象,釋放內(nèi)存");} }?
?配置bean的init-method,destroy-method屬性
<?xml version="1.0" encoding="UTF-8"?> <!-- 引用Spring的多個(gè)Schema空間的格式定義文件 --> <beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"xmlns:context="http://www.springframework.org/schema/context"xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx.xsd "><!-- 定義bean的生命始末方法,自定義方法參與到spring創(chuàng)建和銷毀對(duì)象的過程中。1>. 在java類中定義方法,方法的原形: public void 方法名(無參數(shù)){...} 2>. 在定義bean的時(shí)候,告訴spring兩個(gè)方法的存在<bean id="xx" class="yy" init-method="" destroy-method="" />--><bean id="someService" class="com.atChina2.service.SomeServiceImpl" init-method="startUp" destroy-method="endDown" scope="singleton"/></beans>測(cè)試方法:
// 獲取容器中對(duì)象信息@Testpublic void test3(){String configLocation = "applicationContext.xml"; // 類路徑的根目錄// 會(huì)創(chuàng)建對(duì)象ApplicationContext ctx = new ClassPathXmlApplicationContext(configLocation);com.atChina2.service.SomeService ss = (com.atChina2.service.SomeService)ctx.getBean("someService");ss.doSome();/** 銷毀方法的執(zhí)行* 1. 關(guān)閉容器,關(guān)閉容器時(shí)會(huì)通知容器中的單例對(duì)象,調(diào)用對(duì)象自己的銷毀方法* 2. 對(duì)象必須是單例的* */((ClassPathXmlApplicationContext)ctx).close();}測(cè)試結(jié)果:?
總結(jié)
以上是生活随笔為你收集整理的spring6:bean的生命始末方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: spring五:获取容器中对象信息
- 下一篇: spring7: di依赖注入--设值注