【问题标题】:Java Spring Boot Config StandardJava Spring Boot 配置标准
【发布时间】: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


【解决方案1】:

这取决于您的应用程序实现

在自动装配的情况下,spring首先尝试按名称自动装配,如果没有找到,则按类型自动装配,然后按构造函数(如果按类型没有找到任何bean)。

在我们没有多个具有相同类型和不同名称的 bean 之前,我们可以使用解决方案 2(我们也可以使用 autowire byName 代替 by constructor ),但如果我们有 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
}

在上面的例子中,我在 Qualifier 的帮助下进行了自动装配(构造函数的自动装配也是如此)

【讨论】:

    猜你喜欢
    • 2015-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-25
    • 1970-01-01
    • 1970-01-01
    • 2018-05-06
    相关资源
    最近更新 更多