SimpleName());
}
/**
* 假设再次方法中打开资源,如网络、文件、数据库等
*/
public void open() {
Log.info("open resource here");
}
/**
* 假设在此方法中关闭所有已打开的资源
*/
public void closeAll() {
Log.info("close all resource here");
}
}
- 配置类SelectBeanConfiguration.java,指定了ResourceManager的生命周期是每次http请求
package com.bolingcavalry.config;
import com.bolingcavalry.service.impl.ResourceManager;
import javax.enterprise.context.RequestScoped;
public class SelectBeanConfiguration {
@RequestScoped
public ResourceManager getResourceManager() {
return new ResourceManager();
}
}
- 再写一个web服务类ResourceManagerController.java,这里面使用了ResourceManager
package com.bolingcavalry;
import com.bolingcavalry.service.impl.ResourceManager;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("/resourcemanager")
public class ResourceManagerController {
@Inject
ResourceManager resourceManager;
@GET
@Produces(MediaType.TEXT_PLAIN)
public String get() {
resourceManager.open();
return "success";
}
}
- 由于ResourceManager的生命周期是RequestScoped,因此每次请求/resourcemanager都会实例化一个ResourceManager,请求结束后再将其销毁
- 现在,业务需求是每个ResourceManager的bean在销毁前,都要求其closeAll方法被执行
- 重点来了,在SelectBeanConfiguration.java中新增一个方法,入参是bean,而且要用Disposes注解修饰,如此,ResourceManager类型的bean在销毁前此方法都会被执行
/**
* 使用了Disposes注解后,ResourceManager类型的bean在销毁前,此方法都会执行
* @param resourceManager
*/
public void closeResource(@Disposes ResourceManager resourceManager) {
// 在这里可以做一些额外的操作,不需要bean参与
Log.info("do other things that bean do not care");
// 也可以执行bean的方法
resourceManager.closeAll();
}
- 最后是单元测试类DisposeTest.java,这里用了注解RepeatedTest表示重复执行,属性值为3,表示重复执行3次
@QuarkusTest
public class DisposeTest {
@RepeatedTest(3)
public void test() {
given()
.when().get("/resourcemanager")
.then()
.statusCode(200)
// 检查body内容
.body(is("success"));
}
}
- 执行单元测试,控制台输出如下图,可见每次请求都有bean创建,也伴随着bean销毁,每次销毁都会执行closeResource方法,符合预期
- 至此,生命周期回调相关的实战就完成了,希望能给您一些参考,接下来的文章会继续深入学习依赖注入相关的知识点
欢迎关注博客园:程序员欣宸
学习路上,你不孤单,欣宸原创一路相伴...