Sobes.tech
Junior — Middle

Can you explain the concept of Primary in the context of Spring and what it is used for?

sobes.tech AI

Answer from AI

In Spring, the @Primary annotation is used to indicate the preferred bean when there are multiple candidates for dependency injection of the same type in the context. This helps avoid conflicts when Spring cannot unambiguously choose which bean to use.

For example, if you have two beans of the same interface and want one of them to be used by default, mark it with @Primary:

@Component
@Primary
public class PrimaryService implements MyService {
    // implementation
}

@Component
public class SecondaryService implements MyService {
    // implementation
}

When autowiring, Spring will select PrimaryService unless specified otherwise.