简体   繁体   中英

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM