项目结构如下:
ResourceBean.java代码:
package com.it.res; import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException; public class ResourceBean { private FileOutputStream out;
private File file; public void init(){
System.out.println("初始化的方法!!!!!--->加载资源");
try {
this.out = new FileOutputStream(file); } catch (FileNotFoundException e) {
e.printStackTrace();
}
} public void destroy(){
System.out.println("销毁的方法!!!--->清理内存");
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
} public FileOutputStream getOut(){
return out;
} public void setFile(File file){
this.file=file;
}
}
DependentBean.java代码:
package com.it.res; import java.io.IOException; public class DependentBean {
ResourceBean bean;
public void write(String ss){
System.out.println("写入资源");
try {
bean.getOut().write(ss.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
} public void init(){
System.out.println("depen--->初始化");
try {
bean.getOut().write("depen---->初始化".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
} public void destroy(){
System.out.println("depen--->销毁");
try {
bean.getOut().write("depen--->销毁".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
} public ResourceBean getBean() {
return bean;
} //设置注入
public void setBean(ResourceBean bean) {
this.bean = bean;
} }
resWrite.xml代码:
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- init-method 指定初始化方法,在构造器注入和setter注入完毕后执行。 destroy-method 只有“singleton”作用域能销毁,“prototype”作用域的一定不能,其他作用域不一定能 lazy-init="true"表示懒加载,不提前初始化Bean,而是只有在真正使用时才创建及初始化Bean-->
<bean id="resourceBean" class="com.it.res.ResourceBean" init-method="init" destroy-method="destroy" lazy-init="true">
<property name="file" value="F:/test/a.txt"> </property><!-- Spring容器能自动把字符串转换为java.io.File -->
</bean> <!-- 指定depends-on 则resourceBean会在dependentBean之前初始化,在dependentBean销毁之后销毁-->
<bean id="dependentBean" class="com.it.res.DependentBean" init-method="init" destroy-method="destroy" depends-on="resourceBean">
<property name="bean" ref="resourceBean"></property>
</bean> </beans>
测试类Test.java代码:
package com.it.res; import org.springframework.context.support.FileSystemXmlApplicationContext; public class Test { @org.junit.Test
public void testDepen(){
FileSystemXmlApplicationContext app = new FileSystemXmlApplicationContext("resources/resWrite.xml");
//一定要注册销毁回调,否则我们定义的销毁方法不执行
app.registerShutdownHook();
DependentBean bean = (DependentBean) app.getBean("dependentBean");
bean.write("\r\n德玛西亚\r\n");
}
}
测试完成,控制打印如下:
文件写入: