Sobes.tech
Junior — Middle

How to make it so that a user can use a previously added bean of the same type after a new bean of this type appears in the library?

sobes.tech AI

Answer from AI

To allow a user to use a previously added bean of the same type after a new bean of that type appears, annotations can be used to distinguish beans, for example, @Qualifier in Spring. This explicitly specifies which bean to use. You can also set a default bean using @Primary, so it is chosen during autowiring.

Example using @Qualifier:

@Component
@Qualifier("oldBean")
public class OldService implements Service {
    // implementation
}

@Component
@Qualifier("newBean")
public class NewService implements Service {
    // new implementation
}

@Service
public class Client {
    private final Service service;

    public Client(@Qualifier("oldBean") Service service) {
        this.service = service;
    }
}

Thus, the user explicitly selects the required bean, and adding a new one does not break existing code.