Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to @Autowired a concrete implementation of a service?

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?

like image 909
UHDante Avatar asked Jul 19 '18 10:07

UHDante


People also ask

Can we Autowired a service?

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.

Do you Autowire interface implementation?

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.

How Autowiring is implemented in Spring?

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.

How do you Autowire a method?

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.


1 Answers

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);

like image 194
Alex Roig Avatar answered Oct 20 '22 08:10

Alex Roig