【发布时间】:2017-10-31 23:23:11
【问题描述】:
我有一个这样的接口层次结构:
public interface Shape {
//code
}
@Component
public class Circle implements Shape {
//code
}
@Component
public class Square implements Shape {
//code
}
我想知道使用 Spring Boot bean 约定连接这些的最佳方法。
解决方案 1:
@Component(value = "Circle")
public class Circle implements Shape {
//code
}
@Component(value = "Square")
public class Square implements Shape {
//code
}
@Configuration
public class ShapeConfig {
@Bean
Foo circleFoo(@Qualifiers("Circle") Shape shape) {
return new Foo(shape);
}
@Bean
Foo squareFoo(@Qualifiers("Square") Shape shape) {
return new Foo(shape);
}
}
解决方案 2:
@Component
public class Circle implements Shape {
//code
}
@Component
public class Square implements Shape {
//code
}
@Configuration
public class ShapeConfig {
@Bean
Foo circleFoo(Circle shape) {
return new Foo(shape);
}
@Bean
Foo squareFoo(Square shape) {
return new Foo(shape);
}
}
在这种情况下,最好的 java/spring 实践是什么?我发现 value 和 @Qualifier 的东西有点冗长,但我想知道具体实现中的布线是否不受欢迎
【问题讨论】:
-
有趣的问题...我没有明确的答案,但在这种情况下,我会选择解决方案 2。我倾向于尽可能避免使用魔法注释。预选赛你没有任何收获,委托给一些如此微不足道的东西似乎毫无意义。
标签: java spring spring-boot javabeans