Skip to content

[Use Case]: use CDI qualifier annotations to select a data source #476

Open
@gavinking

Description

@gavinking

As a ...

  • Application user/user of the configuration itself
  • API user (application developer)
  • SPI user (container or runtime developer)
  • Specification implementer

I need to be able to ...

specify the data source that backs a repository via CDI qualifier annotations.

Which enables me to ...

avoid the use of stringly-typed names.

Additional information

Currently, a datasource, persistence unit, etc, that backs a repository implementation must be specified using @Repository(dataStore=".....") which works, but is not properly integrated with the CDI bean manager.

It would be nice to be able to disambiguate the data source or persistence unit or whatever via the placement of CDI qualifier annotations on the repository interface. Unfortunately, there's no obvious completely natural place to put them.

  • Interfaces don't have constructors, so we can't put them on a constructor parameter.
  • Interfaces don't have non-static fields, so we can't put them there either.
  • A qualifier annotation on the interface itself is most naturally interpreted as specifying the CDI qualifiers of the repository itself, not of the datasource backing it.

So, the only options I can really imagine are the following.

Use of method injection

The data source could be viewed as being injected via a method, which is a concept which does already exist in CDI.

@Repository
interface DocumentRepo {

    @Inject 
    void init(@DocumentDatabase DataSource ds);

     ...

}

The problem with this is that it exposes to clients the possibility of manipulating the state of the repository. (And interface methods are always public.)

So this is no good. I would say we definitely don't want to do it this way.

Annotate the resource access method

I actually think this option is pretty good and natural. Probably most repositories are going to want to have a resource accessor method, and so that's a place we can put these annotations.

@Repository
interface DocumentRepo {

    @DocumentDatabase 
    DataSource datasource();

     ...

}

It's true that this is a non-standard place to place qualifier annotations in the sense that it's not contemplated by the CDI spec, but to me that's completely fine. The repository implementation can easily obtain the qualifiers from this method declaration and use them to look up the data source at runtime. Alternatively, an annotation processor can copy them onto an injection point of the repository implementation.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions