我不确定如何在Spring的桥设计模式中注入抽象类及其扩展。让我们考虑一下shape的经典桥梁设计模式示例:
Color.java
public interface Color {
String fill();
}Blue.java
@Service("Blue")
public class Blue implements Color {
@Override
public String fill() {
return "Color is Blue";
}
}Red.java
@Service("Red")
public class Red implements Color {
@Override
public String fill() {
return "Color is Red";
}
}Shape.java
public abstract class Shape {
protected Color color;
@Autowired
private Something something;
@Value(${foo.bar})
private String fooBar;
public Shape(Color color){
this.color = color;
}
abstract public String draw();
}Square.java
public class Square extends Shape {
public Square(Color color) {
super(color);
}
@Override
public String draw() {
return "Square drawn. " + color.fill();
}
}Triangle.java
public class Triangle extends Shape {
public Triangle(Color color) {
super(color);
}
@Override
public String draw() {
return "Triangle drawn. " + color.fill();
}
}BridgeApplication.java
@SpringBootApplication
public class BridgeApplication {
public static void main(String[] args) {
SpringApplication.run(BridgeApplication.class, args);
}
}控制器:
@RestController
public class BridgeController {
@Autowired
@Qualifier("Red")
private Color red;
@GetMapping("/red")
@ResponseStatus(HttpStatus.OK)
public String redSquare() {
Shape square = new Square(red);
return square.draw();
}
}当我们想要注入抽象类Shape或它的扩展(如Square或Triangle )时,问题就出现了。由于构造函数接受Color对象,并且我们无法确定Color是Red类型还是Blue类型(这就是在这里使用Bridge设计模式的全部要点),因此我们不能将Shape或其扩展定义为Spring Bean,因为将有多个Color类型的Bean可用。简单的变通方法类似于我直接构造对象而不是注入它。然而,现在我注入的任何值或我想要注入到Shape类或其扩展(如fooBar或something)中的任何其他Bean都将面临所有挑战,因为相应的类是手动构造的。
一种解决方案是开始处理手动注入,这将通过值和bean注入创建大量不必要的复杂性,而且这根本不是一个干净的解决方案。比如this或指的是this question。所以我想知道在Spring框架中是否有某种形式的Bridge设计模式的干净方式,或者由于Spring的限制,没有。
发布于 2020-04-28 12:11:12
您可以从ApplicationContext.But获取bean,您需要传递颜色才能获取bean...
这里有一个例子:
@RestController
public class BridgeController {
private final Color red;
private final Shape redSquareShape;
public BridgeController(@Qualifier("Red") Color red,
ApplicationContext applicationContext) {
this.red = red;
this.redSquareShape = (Shape) applicationContext.getBean("square", red);
}
@GetMapping("/red")
@ResponseStatus(HttpStatus.OK)
public String redSquare() {
Shape square = new Square(red);
return square.draw();
}
}https://stackoverflow.com/questions/61471066
复制相似问题