我有一个SpringBoot应用程序,它加载一些配置,并在带有@PostConstract注释的方法中运行一个长时间的处理。如果应用程序成功完成或出现错误,则应该释放一些资源。
问题是如何使应用程序资源得到最正确的发布?这是否足以使其在@PreDestroy注释方法中生效,或者我也应该捕获@PostConstract注释方法中的异常。
@SpringBootApplication
@Import(MyConfiguration.class)
public class MySpringApplication {
@Autowire
ProcessRunner processRunner;
@Autowire
ResourceBean resourceBean;
public static void main(String[] args) {
SpringApplication.run(MySpringApplication.class, args);
}
@PostConstruct
void postConstruct {
try {
processRunner.run()
} catch (Exception ex) {
// Do we really need this Exception handling to release resource?
resourceBean.release();
}
}
@PreDestroy
void preDestroy() {
resourceBean.release();
}
}发布于 2018-10-11 13:41:35
当上下文释放bean时,PreDestroy充当回调(即,在上下文关闭时)。这意味着PreDestroy与PostConstruct不耦合。如果bean存在于上下文中并被释放,则将调用预销毁。
PostConstruct意味着初始化bean。如果引发异常,应用程序将不会启动。
所以回答你的问题..。
如果我们在构建后得到异常,是否允许预销毁-方法调用?
PreDestroy和PostConstruct不耦合。这意味着,如果PostConstruct获得了异常,但以某种方式进行了管理,并且该方法成功结束,那么bean将被初始化,并且它将在上下文中可用。当时间到了,上下文关闭时,bean将被释放,PreDestroy将被调用。
如果PostConstruct抛出异常,Bean将在上下文中不可用(应用程序也不会启动),因此不会调用PreDestroy。
问题是如何使应用程序资源得到最正确的发布?这是否足以使其在@PreDestroy注释方法中生效,或者我也应该捕获@PostConstract注释方法中的异常?
您应该捕获异常并释放任何非托管资源。这也适用于JEE,它指定作为最佳实践,必须以编程方式处理在上下文之外获得的资源。
发布于 2018-10-11 13:45:55
@PostConstruct和@PreDestroy注释允许您为bean定义生命周期回调(详见文档 )。
如果@PostConstruct注释的方法可能抛出异常,则应该捕获它们并相应地处理资源的发布。请考虑以下示例:
@SpringBootApplication
public class MySpringApplication {
public static void main(String[] args) {
SpringApplication.run(MySpringApplication.class, args);
}
@PostConstruct
public void init() {
System.out.println("@PostConstruct method executed");
throw new RuntimeException();
}
@PreDestroy
public void destroy() {
System.out.println("@PreDestroy method executed");
}
}在这种情况下,不会执行@PreDestroy注释的方法。
https://stackoverflow.com/questions/52760613
复制相似问题