Search code examples
javaspringcdi

Equivalent to @Inject @Active of CDI in Spring


with CDI, you can do something like this:

@Inject @Active
UserFactory userFactory;

The code means: I want an userFactory that returns only active users.

What is the equivalent way of Spring? I did my research but the nearest I found was Spring profiles. It looks like:

@Autowired @Profiles("active")
UserFactory userFactory;

The problem is only one profile can be actived at the same time, correct? If so, it looks more like @Alternative in CDI to me and it doesn't solve the problem I mentioned.


Solution

  • Spring can also use qualifiers (defined with @Qualifier). Probably the @Active is already a @Qualifier and as such can be used to determine which one to use.

    @Component
    @Active
    public ActiveUserFactory implements UserFactory { ... }
    

    Then in the place you want to use this one add the @Active qualifier again.

    @Autowired
    @Active
    private UserFactory userFactory;
    

    If you don't want to create an annotation you could also use a plain @Qualifer("active") for instance.

    For a more elaborate explanation you might want to check the reference guide.