有时候需要在bean的生命始末做一些自己的操作
接口
package com.hk.spring.ba06;
public interface ISomeSerice {
public String
doFirst();
public void doSecond();
}
接口实现类
package com.hk.spring.ba06;
public class ISomeServiceImpl implements ISomeSerice {
public ISomeServiceImpl() {
System.out.println(
"无参构造器被执行");
}
public ISomeServiceImpl(
int a) {
System.out.println(
"无参构造器被执行"+a);
}
@Override
public String
doFirst() {
System.out.println(
"执行doFirst");
return "hello spring";
}
@Override
public void doSecond() {
System.out.println(
"执行doSecond");
}
public void initAfter(){
System.out.println(
"初始化之后");
}
public void perDestroy(){
System.out.println(
"销毁之前");
}
}
bean配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="someService" class="com.hk.spring.ba06.ISomeServiceImpl" init-method="initAfter" destroy-method="perDestroy"/>
</beans>
测试方法
package com.hk.spring.ba06;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Mytest {
/**
* 定制bean的生命始末
*/
@Test
public void test_1(){
String resource =
"/com/hk/spring/ba06/applicationContext.xml";
ApplicationContext ac =
new ClassPathXmlApplicationContext(resource);
ISomeSerice iSomeService = (ISomeSerice) ac.getBean(
"someService");
String result = iSomeService.doFirst();
System.out.println(result);
iSomeService.doSecond();
((ClassPathXmlApplicationContext) ac).close();;
}
}
运行结果
无参构造器被执行
初始化之后
执行
doFirst
hello spring
执行
doSecond
销毁之前
转载请注明原文地址: https://ju.6miu.com/read-200336.html