mercredi 8 avril 2020

Spring inject two implementations of an interface to use bridge design pattern

I have implemented a sample of bridge design pattern in my application that uses Spring boot. I was wondering how I could manage to inject different implementations of an interface. Obviously, if I try to inject them it throws the required a single bean, but 2 were found I would appreciate it if you could help to understand how this can be achieved in conjunction with dependency injection:

public interface Color {
    String fill();
}

@Service
public class Blue implements Color {
    @Override
    public String fill() {
        return "Color is Blue";
    }
}

@Service
public class Red implements Color {
    @Override
    public String fill() {
        return "Color is Red";
    }
}

public abstract class Shape {
    protected Color color;

    //standard constructors

    abstract public String draw();
}

@Service
public class Square extends Shape {

    public Square(Color color) {
        super(color);
    }

    @Override
    public String draw() {
        return "Square drawn. " + color.fill();
    }
}

Test it:

@Autowired
private Red red;

@Test
public void whenBridgePatternInvoked_thenConfigSuccess() {


    //a square with red color
    Shape square = new Square(red);

    assertEquals(square.draw(), "Square drawn. Color is Red");
}

Aucun commentaire:

Enregistrer un commentaire