pixel
pixel

Reputation: 26441

ConditionalOnMissingBean over Primary?

I've noticed in some of spring libraries that most of the beans are annotated with @ConditionalOnMissingBean.

Is there any advantage over not using any condition and make use of @Primary in main code, or it is just matter of having less annotations?

Upvotes: 0

Views: 2141

Answers (2)

Bahadir Tasdemir
Bahadir Tasdemir

Reputation: 10783

The definition for @Primary (docs):

Indicates that a bean should be given preference when multiple candidates are qualified to autowire a single-valued dependency. If exactly one 'primary' bean exists among the candidates, it will be the autowired value.

The definition for @ConditionalOnMissingBean (docs):

Conditional that only matches when the specified bean classes and/or names are not already contained in the bean factory.

In short:

@Primary -> to enforce,

@ConditionalOnMissingBean -> to fallback

Upvotes: 6

Makoto
Makoto

Reputation: 106389

You can think of @ConditionalOnMissingBean like a fallback. This bean will be registered if there is no other bean like it that can be found in the context path.

A @Primary bean primarily deals with priority. A bean annotated with that will be registered first, which typically implies that it's the only bean that will be used.

Using conditional beans depends on what you're doing. If you have several services which serve different purposes and should not be wired at the same time, a conditional wiring is perfect for that scenario. If you only ever have or will only ever need one bean, or you're getting a bean (like a dataSource from an upstream library, it's useful to specify the bean you want to wire as the only one that should be considered.

Upvotes: 2

Related Questions