QA's approach to Java - Dependency Injection
Dependency injection defined with Real world analogy:
Ecommerce site has dependency on Delivery service1. Create a package DependencyInjectionExample
2. Create an interface for Courier Service with delivery method
package DependencyInjectionExample;
public interface CourierService {
public void deliver(int Pid);
}
3. Create a class for various courier services implementing delivery method of interface Courier Service
DTDC service class implementing Courier Service interface
package DependencyInjectionExample;
public class DTDC implements CourierService{
@Override
public void deliver(int Pid) {
System.out.println("Product with deliverly id"+Pid+" is delivered through DTDC");
}
DTDC()
{
}
}
BlueDart service class implementing Courier Service interface
package DependencyInjectionExample;
class BlueDart implements CourierService{
@Override
public void deliver(int Pid) {
// TODO Auto-generated method stub
System.out.println("Product with deliverly id"+Pid+" is delivered through BlueDart");
}
}
4. Create E commerce service class utilizing delivery service dynamically
package DependencyInjectionExample;
public class DepdencyInjecttionTest {
public static void main(String args[]) {
// Loose coupling - decide the delivery service at Runtime
CourierService cs = null;
try {
cs = (CourierService) Class.forName(args[0]).newInstance();
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Alibaba uses the decided delivery service to send the product
Alibaba ab = new Alibaba(cs);
ab.send(101);
}
}
@Override
public void deliver(int Pid) {
System.out.println("Product with deliverly id"+Pid+" is delivered through DTDC");
}
DTDC()
{
}
}
BlueDart service class implementing Courier Service interface
package DependencyInjectionExample;
class BlueDart implements CourierService{
@Override
public void deliver(int Pid) {
// TODO Auto-generated method stub
System.out.println("Product with deliverly id"+Pid+" is delivered through BlueDart");
}
}
4. Create E commerce service class utilizing delivery service dynamically
package DependencyInjectionExample;
public class DepdencyInjecttionTest {
public static void main(String args[]) {
// Loose coupling - decide the delivery service at Runtime
CourierService cs = null;
try {
cs = (CourierService) Class.forName(args[0]).newInstance();
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Alibaba uses the decided delivery service to send the product
Alibaba ab = new Alibaba(cs);
ab.send(101);
}
}
The Package looks as follows:
How to run the Java program in eclipse with runtime parameters
Navigate to Run Configurations window & in there, follow the below
Use Alt+Shift+X,J
Comments
Post a Comment