欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

spring6:bean的生命始末方法

发布时间:2025/6/15 编程问答 38 豆豆
生活随笔 收集整理的这篇文章主要介绍了 spring6:bean的生命始末方法 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

 

package com.atChina2.service;public class SomeServiceImpl implements SomeService {public SomeServiceImpl(){System.out.println("SomeServiceImpl...无参构造函数..");}@Overridepublic void doSome() {System.out.println("doSome业务方法...");}// 定义bean的生命始末方法,自定义方法参与到spring创建和销毁对象的过程中。// 初始化方法public void startUp(){System.out.println("bean的初始化方法,可以完成构造方法的功能,给属性赋值,初始化其他对象");}// bean销毁之前执行的方法public void endDown(){System.out.println("bean对象销毁之前执行的方法,清楚对象,释放内存");} }

 

 配置bean的init-method,destroy-method属性

<?xml version="1.0" encoding="UTF-8"?> <!-- 引用Spring的多个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创建和销毁对象的过程中。1>. 在java类中定义方法,方法的原形: public void 方法名(无参数){...} 2>. 在定义bean的时候,告诉spring两个方法的存在<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>

测试方法:

// 获取容器中对象信息@Testpublic void test3(){String configLocation = "applicationContext.xml"; // 类路径的根目录// 会创建对象ApplicationContext ctx = new ClassPathXmlApplicationContext(configLocation);com.atChina2.service.SomeService ss = (com.atChina2.service.SomeService)ctx.getBean("someService");ss.doSome();/** 销毁方法的执行* 1. 关闭容器,关闭容器时会通知容器中的单例对象,调用对象自己的销毁方法* 2. 对象必须是单例的* */((ClassPathXmlApplicationContext)ctx).close();}

测试结果: 

总结

以上是生活随笔为你收集整理的spring6:bean的生命始末方法的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。