java - Spring Dependency injection using interface with more than one implementation -
my question has been asked here in following link.
spring: why autowire interface , not implemented class?
what want know if use @qualifier
inject bean purpose of autowiring interface ?? why not auto-wire same implementation class ??
by autowiring interface want take advantage of run-time polymorphism that's not achieved if follow approach of @qualifier
. please suggest me standard way.
following simple code if without spring. wonder how spring inject prepaidpaymentservice instance , postpaidpaymentservice instance??
public interface paymentservice{ public void processpayment(); } public class prepaidpaymentservice implements paymentservice{ public void processpayment(){ system.out.println("its prepaid payment service"); } } public class postpaidpaymentservice implements paymentservice{ public void processpayment(){ system.out.println("its postpaid payment service"); } } public class test { public paymentservice service; public static void main(string[] args) { test test = new test(); int = 1; if(i ==1 ){ test.setservice(new prepaidpaymentservice()); test.service.processpayment(); } = 2; if(i == 2){ test.setservice(new postpaidpaymentservice()); test.service.processpayment(); } } public void setservice(paymentservice service){ this.service = service; } }
one reason autowiring interface (even @qualifier
) can inject different implementation testing purposes.
for example, if have service uses dao access database, might want replace dao in order unit-test service. autowiring on interfa
Comments
Post a Comment