I have the following situation:
public interface ServiceAura extends Serializable { }
@Service
public class ServiceA implements ServiceAura {
....
}
@Service
public class ServiceB implements ServiceAura {
....
}
Now from the controller I need to call both of them by separate:
@Path("")
@Controller
public class ServiciosAuraPortalRESTfulService {
@Autowired
private ServiceAura srvA;
@Autowired
private ServiceAura srvB;
}
I have read about @Qualified, is this the only way? How can I archive this?
If you want properly use @Autowired in your spring-boot application, you must do next steps: Add @SpringBootApplication to your main class. Add @Service or @Component annotation to class you want inject. Use one of two ways that you describe in question, to autowire.
You autowire the interface so you can wire in a different implementation--that's one of the points of coding to the interface, not the class.
In Spring, you can use @Autowired annotation to auto-wire bean on the setter method, constructor , or a field . Moreover, it can autowire the property in a particular bean. We must first enable the annotation using below configuration in the configuration file. We have enabled annotation injection.
The @Autowired annotation provides more fine-grained control over where and how autowiring should be accomplished. The @Autowired annotation can be used to autowire bean on the setter method just like @Required annotation, constructor, a property or methods with arbitrary names and/or multiple arguments.
You're right. You can use @Qualifier("ServiceA")
to specify which implementation you want to autowire.
@Path("")
@Controller
public class ServiciosAuraPortalRESTfulService {
@Autowired
@Qualifier("ServiceA")
private ServiceAura srvA;
@Autowired
@Qualifier("ServiceB")
private ServiceAura srvB;
}
On the service itself, you can use the annotation @Primary
to specify which one is the default implementation that you want.
Alternatively, you can use the application context to retrieve a specific bean. You'll need to autowire the ApplicationContext
class and then retrieve it with ServiceAura srvA = context.getBean(ServiceA.class);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With