Skip to content

AutoCloseable beans #876

@gavinking

Description

@gavinking

I've recently been trying out Spring for the first time, in order to get Hibernate Data Repositories working with it. To my surprise, Spring's support for dependency injection is on the whole quite inelegant and still, after all these years, lacking in type safety compared to CDI. It looks like at one point in history they basically just put a veneer of annotations over their old XML stuff, and then sorta left it at that. The annotations themselves are a real hodgepodge strewn about various packages, with quite bad naming, For example, their equivalent of @Produces is called @Bean and has seven weird and messy-looking members, most of them stringly-typed.

But there is so far one single thing I've run into that I liked, and that is missing in CDI.

It seems that by default Spring will automatically call the close() method of any bean which implements AutoCloseable. In CDI I would have two options:

  1. declare a @PreDestroy method if it's a regular bean, or
  2. write a @Disposes method if it's a producer method.

Option 1 is in general completely fine, and arguably @PreDestroy is easier than implementing AutoCloseable. But option 2 for producer methods is actually significantly worse, since it's very common that the object returned by a producer method is defined by a library or framework, and already implements AutoCloseable. For example, Hibernate's StatelessSession, or whatever.

I think there should be some way to indicate to CDI that it should treat the close() method as a @PreDestroy callback. Ideally this would be automatic, but that would break backward compatibility, so I guess we need some sort of annotation for that. I'm not sure of the best way to expose that, but perhaps something like this is OK, if not perfect:

@Produces @Closeable @TransactionScoped
StatelessSession statelessSession(SessionFactory factory) {
    return factory.openStatelessSesssion();
}

Does anyone have a better idea?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions