一个接口依赖另一个接口的三种方法(非注释)

不使用框架的自动注入之前,是这个样子的:

方式一:通过接口传递实现依赖

public class Dependency {
    public static void main(String[] args) {
        InterfaceBImpl inB = new InterfaceBImpl();
        InterfaceAImpl inA = new InterfaceAImpl();
        inA.methodA(inB);
    }
}

interface InterfaceA{
    public void methodA(InterfaceB b);
}

interface InterfaceB{
    public void methodB();
}

class  InterfaceBImpl implements InterfaceB{
    @Override
    public void methodB() {
        System.out.println("我是接口B的方法");

    }
}

class InterfaceAImpl implements InterfaceA{
    @Override
    public void methodA(InterfaceB b) {
        b.methodB();
    }
}

即接口A调用了接口B。

方式二:通过构造方法传递

public class Dependency {
    public static void main(String[] args) {
        InterfaceBImpl inB = new InterfaceBImpl();
        InterfaceAImpl inA = new InterfaceAImpl(inB);
        inA.methodA();
    }
}

interface InterfaceA{
    public void methodA();
}

interface InterfaceB{
    public void methodB();
}

class  InterfaceBImpl implements InterfaceB{
    @Override
    public void methodB() {
        System.out.println("我是接口B的方法");

    }
}

class InterfaceAImpl implements InterfaceA{
    public InterfaceB b;
    public InterfaceAImpl(InterfaceB b){
        this.b = b;
    }
    @Override
    public void methodA() {
        this.b.methodB();
    }
}

方式三:通过set方法传递

public class Dependency02 {
    public static void main(String[] args) {
        InterfaceAImpl inA = new InterfaceAImpl();
        InterfaceBImpl inB = new InterfaceBImpl();
        inA.setInterfaceB(inB);
        inA.methodA();
    }
}

interface InterfaceA{
    public void methodA();
    public void setInterfaceB(InterfaceB b);
}

interface InterfaceB{
    public void methodB();
}

class InterfaceAImpl implements InterfaceA{
    private InterfaceB b;

    @Override
    public void setInterfaceB(InterfaceB b) {
        this.b = b;
    }

    @Override
    public void methodA() {
        this.b.methodB();
    }

}

class InterfaceBImpl implements InterfaceB{
    @Override
    public void methodB() {
        System.out.println("我是接口B的方法");
    }
}

使用框架的自动注入之后,是这个样子的: 

public class InterfaceAImpl implements InterfaceA{
	@Autowired
	protected InterfaceB interfaceB;
        /*
        .
        .
        .
        */
}

简单了很多很多很多...

你可能感兴趣的:(实际开发问题总结)