我有一个像这样的接口层次结构:
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练习是什么?我发现值和@Qualifier的东西有点冗长,但我想知道具体实现中的连接是否是不受欢迎的
答案 0 :(得分:1)
这取决于您的应用程序实现
在autowire的情况下,spring首先尝试通过名称自动装配,然后如果没有找到它按类型然后通过构造函数(如果没有找到任何类型的bean)。
在我们没有多个具有相同类型和不同名称的bean之前,我们对解决方案2很好(我们也可以使用autowire byName而不是构造函数),但是如果我们有2个或更多,那么2个相同类型的bean然后我们去解决方案1(限定符) 例如:
@Configuration
public class Config {
@Bean(name = "circle1")
public Circle getCircle1(){
Circle c = new Circle();
c.setRadius(1.5);
return c;
}
@Bean(name = "circle2")
public Circle getCircle2(){
Circle c = new Circle();
c.setRadius(10);
return c;
}
}
假设我有服务
@Component
CirculeService {
@Autowire @Qualifier("circle1") Circle circle1
@Autowire @Qualifier("circle2") Circle circle2
}
以上exapme我在限定符的帮助下有autowire(由构造函数的autowire相同)