Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@PreDestroy never called on @ViewScoped [duplicate]

I have a @ViewScoped bean that has a method with an @PreDestroy annotation that should make sure some remote connections are closed. However, the method is not called when the user navigates away.

Is there anything one can do wrong? Do I have to register anything anywhere in order to make it work?

It's a simple public method (void) that throws no exception.

I'm using JSF 2 (MyFaces) with Tomcat 7.0.12. Could it be a problem with Tomcat?

UPDATE

The @PostConstruct annotation works fine.

like image 989
geeehhdaa Avatar asked Jun 16 '11 08:06

geeehhdaa


People also ask

What is the difference between @PreDestroy and PostConstruct?

@PreDestroy A method annotated with @PreDestroy runs only once, just before Spring removes our bean from the application context. Same as with @PostConstruct , the methods annotated with @PreDestroy can have any access level but can't be static.

When does PreDestroy get called in spring bean?

When we annotate a Spring Bean method with PreDestroy annotation, it gets called when the bean instance is getting removed from the context. Remember that if your spring bean scope is “prototype” then it’s not completely managed by the spring container and the PreDestroy method won’t get called.

What is the purpose of @PreDestroy in Java?

Same as with @PostConstruct , the methods annotated with @PreDestroy can have any access level but can't be static. The purpose of this method should be to release resources or perform any other cleanup tasks before the bean gets destroyed, for example closing a database connection. 4. Java 9+

Are @PostConstruct and @PreDestroy annotations part of Java EE?

Developers, who are using Java 9+, both @PostConstruct and @PreDestroy annotations are part of Java EE. And since Java EE has been deprecated in Java 9 and removed in Java 11 we have to add an additional dependency to use these annotations: A.


1 Answers

This is a known issue and unfortunately not trivial to solve without letting all the navigation take place through the view scoped bean in question. See also JSF-impl issue 1839. This does only not cover cases where the enduser changes the URL in browser address bar or closes the window/tab. Their @PreDestroy will also not be called when the session get destroyed. An enhancement request for the specification has however been posted to get the dangling views to destroy during session destroy anyway: JSF-spec issue 905.

like image 192
BalusC Avatar answered Sep 30 '22 02:09

BalusC